Page 1 of 1

Openfile() wasting time.

Posted: Mon Dec 04, 2023 2:29 pm
by matalog
I'm using a strange method of sending data, over WIFI to a WIFI SD Card, and trying to stream to it. It seems to have the biggest problem using Openfile() on the WIFI card, it takes 1-3 seconds to complete, and in my program this stops the whole program running as it waits.

I would not close any files if the data was updated on receiving device, but it isn't updated until I Closefile().

How could I program the Closefile() and a new Openfile() to run parallel to the running of the program, and not stall my program?

Another option would be to open many files at the start of the program, and then close them as it runs (Closefile() ) doesn't seem to stall the program as much.

Any ideas?

Re: Openfile() wasting time.

Posted: Mon Dec 04, 2023 3:07 pm
by Fred
You need to use threads

Re: Openfile() wasting time.

Posted: Tue Dec 05, 2023 12:05 am
by matalog
Fred wrote: Mon Dec 04, 2023 3:07 pm You need to use threads
Yes, I do, I don't know much about using them, but seem to have something almost working. Thanks.

Re: Openfile() wasting time.

Posted: Tue Dec 05, 2023 12:24 am
by BarryG
This should explain it better. It simulates writing a slow file to disk while not slowing down the main loop (the counter never stops).

Code: Select all

CompilerIf #PB_Compiler_Thread=0
  MessageRequester("Compile Error","Thread-safety is not enabled!",#PB_MessageRequester_Error)
  End
CompilerEndIf

Procedure SimulateSlowFile(null=0)
  DisableGadget(0,#True)
  SetGadgetText(2,"Writing file...")
  f$=GetTemporaryDirectory()+"slow-file-test.txt"
  f=OpenFile(#PB_Any,f$)
  If f
    Delay(5000) ; 5-second delay to simulate a slow write.
    CloseFile(f)
    DeleteFile(f$) ; Don't leave it behind after this test. ;)
  EndIf
  SetGadgetText(2,"")
  DisableGadget(0,#False)
EndProcedure

OpenWindow(0,200,200,300,100,"Test",#PB_Window_SystemMenu)
ButtonGadget(0,10,10,280,25,"Click to write file to disk")
TextGadget(1,10,40,100,20,"")
TextGadget(2,10,60,100,20,"")
AddWindowTimer(0,0,50)

Repeat
  ev=WaitWindowEvent()
  If ev=#PB_Event_Timer
    n+1
    SetGadgetText(1,Str(n))
  ElseIf ev=#PB_Event_Gadget
    If EventGadget()=0
      writing=CreateThread(@SimulateSlowFile(),0)
    EndIf
  EndIf
Until ev=#PB_Event_CloseWindow And IsThread(writing)=0

Re: Openfile() wasting time.

Posted: Tue Dec 05, 2023 9:58 am
by mk-soft
matalog wrote: Tue Dec 05, 2023 12:05 am
Fred wrote: Mon Dec 04, 2023 3:07 pm You need to use threads
Yes, I do, I don't know much about using them, but seem to have something almost working. Thanks.
Show Mini Thread Control with many examples ;)

Re: Openfile() wasting time.

Posted: Thu Dec 07, 2023 11:02 pm
by matalog
Thanks for that :-).