Wait until readfile has finished

Just starting out? Need help? Post your questions and find answers here.
AMpos
Posts: 42
Joined: Mon Aug 03, 2020 5:15 pm

Wait until readfile has finished

Post 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())
User avatar
Peter
Posts: 1086
Joined: Mon Feb 24, 2014 10:17 pm
Location: 127.0.0.1:9080
Contact:

Re: Wait until readfile has finished

Post 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.
Post Reply