B4J Question What is the recommended way to perform a time-consuming task?

xulihang

Well-Known Member
Licensed User
Longtime User
There is a sub which is time consuming. I try to make it a resumable sub but it is still making the UI not responsive.

So I use the Threading library to call the sub.


B4X:
Private th As Thread
th.Initialise("th")
Dim map1 As Map
map1.Initialize
map1.Put("mat",Mat)
map1.Put("geometries",geometries)
th.Start(Me,"Detect",Array As Map(map1))
wait for th_Ended(endedOK As Boolean, error As String)

It works but on some devices, the th_Ended event is never triggered. One of my users is reporting this: https://github.com/xulihang/ImageTrans-docs/issues/1029

I can reproduce this on a Linux Virtual machine with limited CPU cores. It works fine on my regular macOS and Windows devices.
 

xulihang

Well-Known Member
Licensed User
Longtime User
I modified the code like the following. If it takes too long, mark it as time out and stop using Threading.

B4X:
Private MergeBoxesIsTimeOut as Boolean = False

Private Sub MergeBoxesUILess(filename As String,srcMat As cvMat,horizontal As Boolean,Xweight As Double,Yweight As Double) As ResumableSub
    MergeBoxesAsync(filename,srcMat,horizontal,Xweight,Yweight)
    wait for Merged(Success As Boolean)
    Return ""
End Sub

Sub MergeBoxesAsync(filename As String,srcMat As cvMat,horizontal As Boolean,Xweight As Double,Yweight As Double)
    If MergeBoxesIsTimeOut Then
        wait for (MergeBoxesUILessImpl(filename,srcMat,horizontal,Xweight,Yweight)) complete (done As Object)
        CallSubDelayed2(Me, "Merged", True)
    Else
        Dim b() As Boolean = Array As Boolean(False)
        MergeBoxesTimeOut(5000, b)
        th.Start(Me,"MergeBoxesUILessImpl",Array(filename,srcMat,horizontal,Xweight,Yweight))
        wait for th_Ended(endedOK As Boolean, error As String)
        If b(0) = False Then
            b(0) = True
            CallSubDelayed2(Me, "Merged", True)
        End If
    End If
End Sub

Sub MergeBoxesTimeOut(Duration As Int, b() As Boolean)
    Sleep(Duration)
    If b(0) = False Then
        MergeBoxesIsTimeOut = True
        b(0) = True
        Log("time out")
        CallSubDelayed2(Me, "Merged", False)
    End If
End Sub

Private Sub MergeBoxesUILessImpl(filename As String,srcMat As cvMat,horizontal As Boolean,Xweight As Double,Yweight As Double) As ResumableSub
'heavy work here
End Sub
 
Upvote 0
Top