Hi. I'm trying to understand how to use threads to do some parallel tasks. Specifically drawing a splash screen while loading some datafiles.
Attached is a small example that illustrates some things I don't yet understand:
This is the code
Attached is a small example that illustrates some things I don't yet understand:
- Why label updates from the thread sub, doesn't happen until the end? And why the text that it prints is always the one from the last call?
- It doesn't seem possible to trigger the Ended event before the Create_Activity sub finishes.
- What I'm doing wrong?
This is the code
B4X:
Sub Process_Globals
Dim SplashStillDrawing As Boolean : SplashStillDrawing = True
Dim SplashThread As Thread
Dim SplashLock As Lock
End Sub
Sub Globals
Dim InfoLabel As Label
Dim InfoLabelText As StringBuilder : InfoLabelText.Initialize
End Sub
Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then Activity.Initialize("MainActivity")
InfoLabel.Initialize("InfoLabel")
Activity.AddView(InfoLabel, 10%x, 10%y, 80%x, 80%y)
InfoLabel.Color = Colors.LightGray
InfoLabel.TextColor = Colors.black
If SplashStillDrawing Then
Log2("splash_YES")
If FirstTime Then
Log2("splash_FIRSTTIME")
SplashThread.Initialise("SplashThread")
SplashLock.Initialize(True)
Dim args(0) As Object
SplashThread.Start("Create_Splash",args)
Log2("After calling Create_Splash")
End If
' Do things....
SplashLock.Wait
Log2("(Splash Finished)")
Wait(3)
Else
Log2("splash_NOT")
End If ' /SplashStillDrawing
Log2("Thread running:" & SplashThread.Running )
'Wait(2)
'Log2("Exiting...")
'Activity.Finish
'ExitApplication
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub Create_Splash
Dim params(1) As Object
params(0) = "> Create_Splash" : SplashThread.RunOnGuiThread("Log2", params)
Wait(3)
SplashThread.Interrupt
params(0) = "> interrupted" : SplashThread.RunOnGuiThread("Log2", params)
SplashLock.Unlock
params(0) = "> unlocked" : SplashThread.RunOnGuiThread("Log2", params)
params(0) = "> returning" : SplashThread.RunOnGuiThread("Log2", params)
Return
End Sub
Sub SplashThread_Ended(fail As Boolean, error As String)
Log2("SplashThread_Ended")
SplashStillDrawing = False
End Sub
Sub Wait(Seconds As Int)
Dim Ti As Long
Ti = DateTime.Now + (Seconds * 1000)
Do While DateTime.Now < Ti
DoEvents
Loop
End Sub
' Logs both to IDE & to Label
Sub Log2(InfoText As String)
Log(InfoText)
InfoLabelText.Append(InfoText & CRLF)
InfoLabel.Text = InfoLabelText.ToString
DoEvents
End Sub
Attachments
Last edited: