parallel.invoke & Win forms Freeze !!

student101

Member
Joined
Dec 22, 2007
Messages
10
Programming Experience
3-5
HI everyone ,
before any attempt to solve my problem , im thankful of anyone who wants to participate to help me ;)
so , i'm Using net 4.0 & i'm learning parallel programming ,
i'm using parallel.invoke to run 2 or more methods with together at a same time .
but i want to update my UI ( listboxes ) while i'm running methods . i can do that with threads & delegates , but now i can't do that , this code is running well
VB.NET:
Imports System.Threading.Tasks
Imports System.Threading
Imports System.IO

Public Class Form1

    Delegate Sub mh(ByVal p As String, ByVal pp As Integer)
    Dim jp As mh
    Dim temp As Integer = 2



    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        jp = AddressOf th3

        Parallel.Invoke(AddressOf th1,addressOf th2)

    End Sub

    Private Sub th1()
        For i = 0 To 106600

              ListBox1.BeginInvoke(jp, i.ToString, 1)

        Next
    End Sub

    Private Sub th2()
        For i = 100 To 12340
              ListBox2.BeginInvoke(jp, i.ToString, 2)
        Next

    End Sub

    Private Sub th3(ByVal p As String, ByVal pp As Integer)
        If pp = 1 Then
            ListBox1.Items.Add(p)
        Else
            ListBox2.Items.Add(p)
        End If
    End Sub

end class
but this code wont update the UI till both method will be finished !
but i can update my UI by using simple thread & calling me.invoke(jp,i.tostring,1) for example
but when i use this piece of code everything will be froze !!!!!!!!!!!!!
VB.NET:
 Private Sub th1()
        For i = 0 To 106600

             ListBox1.Invoke(jp, i.ToString, 1)

        Next
    End Sub
i dont know why me.invoke or listbox1.invoke wont work with parallel.invoke ! if somebody can help me how can i update my UI While its adding to my listbox i'll be thanksful
 
Parallel.Invoke is a blocking call, it doesn't return until all actions has completed, which means you have tied up the UI thread from the get-go. Also beware that methods of Parallel class may do part of their work on current thread. Check this article Potential Pitfalls in Data and Task Parallelism

Coming to the tasks, your worker methods has no actual work load, they just run a loop that posts to UI thread, so that does not give the UI thread any room to breathe. If you added a Thread.Sleep(1) within the loop to simulate even the slightest async work time you would see UI thread starting to respond. But before any of that is happening you have to start your tasks asynchronous and non-blocking, for that you can use the Task.Factory.StartNew method for example.
 
Back
Top