MojoDK
MojoDK

Reputation: 4538

Threadding: Update UI without blocking the thread?

I have written a server program that does a lot of jobs in threads simultaneously.

In those threads, I have to update a ListView with status information, but as it is right now using invoke, the thread waits for the UI to finish updating the ListView.

Any good advice to how I can send the status to the ListView and continue the thread while ListView finish updating?

Here's my code...

Public Delegate Sub InfoDelegate(status As String)

Public Sub Info(status As String)
    If Me.InvokeRequired Then
        Dim d As New InfoDelegate(AddressOf Info)
        Me.Invoke(d, status)
    Else
        Dim item As New ListViewItem With {
            .Text = status}

        With lv
            .BeginUpdate()
            .Items.Insert(0, item)
            If .Items.Count > 500 Then
                For i As Integer = Me.lv.Items.Count - 1 To 500 Step -1
                    Me.lv.Items.RemoveAt(i)
                Next
            End If
            .EndUpdate()
        End With
    End If
End Sub

Upvotes: 2

Views: 436

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18330

You can call Control.BeginInvoke() to invoke the method asynchronously. However that call needs to be followed by a EndInvoke() call, or else you will get memory and/or thread leaks.

In the .NET Framework versions 4.0 and up you can utilize lambda expressions to pass the IAsyncResult returned from the BeginInvoke call to the lambda expression itself. Thus, you can call EndInvoke without having it block since by the time that it is called the asynchronous operation is already finished.

Here's an example:

Dim iar As IAsyncResult = _
    Me.BeginInvoke(Sub()
                                   Info("Status here") 'Calling your Info() method.
                                   Me.EndInvoke(iar)
                               End Sub)

Upvotes: 2

Related Questions