Friday, June 22, 2007

Using Cross Control Thread in .Net 2.0

This article discuss about the using of Thread in .Net 2.0. In the previous framework (.Net 1.1), it is easy to create a thread cross between control or class. But we can not use the same method for .Net 2.0. We should use a callback that delegate enables asynchronous calls to cross thread control.

First step, we define the thread.

'define thread for translation
Private threadTranslation As System.Threading.Thread

Second step, we call a ThreadTranslation function to start the process.

'create a process thread, then start translation
If IsNothing(threadTranslation) OrElse Not threadTranslation.IsAlive Then
threadTranslation = New System.Threading.Thread(AddressOf ThreadTranslation)
threadTranslation.Start()
End If

The first and second step are same with the .Net 1.1. procedures.

The next third step is different, we add a delegate function as a callback. The public function will invoke the callback function if the caller from different thread.

' This delegate enables asynchronous calls to cross thread control
Delegate Function GetDictionaryTextCallback() As String

Public Function GetDictionaryText() As String
Dim strText As String = ""
Try
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If txtDictionary.InvokeRequired Then
Dim d As New GetDictionaryTextCallback(AddressOf GetDictionaryText)
strText = Me.Invoke(d, New Object() {})
Else
strText = txtDictionary.Text
End If
Return strText
Catch ex As Exception
Throw ex
End Try
End Function

The ThreadTranslation function will call GetDictionaryText function from different thread. The GetDictionaryText will invoke the callback function.
The result will be successfully written into textbox in the different thread.

I use this method in my Bahasa Professional project.