Saturday, 17 August 2013

Vb.Net - Invoke in Task

Vb.Net - Invoke in Task

so basically I want my application to run a method that is quite cpu
intensive and therewhile it should constantly display status information
on a different form. To prevent this status form from freezing, I thought
it would be a good idea to outsource the code into a new thread.
First I tried to use basic threadding and invoking the richtextbox control
which should display status messages. - Problem is - I need to know when
the Thread is finished to carry on with my main thread. Obviously I cannot
simply run a loop in my main thread that keeps checking if the process is
finished, cause that would make my GUI freeze, too.
So I did a little bit research and found out about Tasks. That's how it
looks:
Dim z as new complexProcessClass
Dim taskA = task.Factory.StartNew(Sub() z.start())
taskA.Wait()
If taskA.IsCompleted Then
MsgBox("finished")
End If
And whenever the process reports a status I use this:
Public Class complexProcessClass
dim statusWindow as statusForm
Public Sub start()
statusWindow = new statusForm
'complex code here
reportStatus("bla")
'complex code here
reportStatus("blabla")
'complex code here
End Sub
Private Delegate Sub UpdateTextHandler(ByVal Text As String)
Private Sub reportStatus(Byval s as String)
If z.RichTextBox1.InvokeRequired Then
Try
z.RichTextBox1.Invoke(New UpdateTextHandler(AddressOf
xform.RichTextBox1.AppendText), s)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Else
z.RichTextBox1.AppendText(s)
End If
End Sub
But it just keeps freezing on the invoke call - no error message - nothing?!
Can anybody tell me the correct way to do this? - and please no
backgroundworker solution ;)
thanks in advance

No comments:

Post a Comment