Page 1 of 1

Wait until readfile has finished

Posted: Tue Mar 09, 2021 11:36 pm
by AMpos
Hi!

I am reading lines from a text file, and adding them to a list.

How can I wait/halt my program until the read-loop has finished?

(example code modifies from help file)

Code: Select all

Global.s NewList t()

Procedure ReadCallback(Status, Filename$, File, Size)
	If Status = #PB_Status_Loaded
		Debug "File: " + Filename$ + " - Size: " + Size + " bytes"
		
		; Read the first 10 lines
		;
		While Eof(0) = 0 And NbLine < 10 
			AddElement(t())
			t()=ReadString(0)  
			NbLine+1
		Wend
		CloseFile(0)
		
	ElseIf Status = #PB_Status_Error
		Debug "Error when loading the file: " + Filename$
	EndIf
EndProcedure

Procedure OpenFileRequesterCallback()
	If NextSelectedFile()
		ReadFile(0, SelectedFileID(), @ReadCallback(), #PB_LocalFile)
	EndIf
EndProcedure

Procedure ChooseFileEvent()
	OpenFileRequester("*.txt", @OpenFileRequesterCallback())
	
	ForEach t()
		Debug t()
	Next
EndProcedure

OpenWindow(0, 0, 0, 300, 50, "Read file example", #PB_Window_ScreenCentered)
ButtonGadget(0, 10, 10, 280, 30, "Choose a file...")

BindGadgetEvent(0, @ChooseFileEvent())

Re: Wait until readfile has finished

Posted: Wed Mar 10, 2021 1:00 pm
by Peter
AMpos wrote:How can I wait/halt my program until the read-loop has finished?
Although this is technically possible, it is not recommended. The browser only executes the JavaScript single-threaded. If you block this thread (because you are waiting for something), the browser freezes.

The file is completely loaded after CloseFile(0) is called in the callback. Only after this can you output the text lines in your LinkedList.