There are number of reasons you want multi-threading on your application. One is making your application interface responsive while its processing another job, because nobody want a screen that freeze until a process is finished. A common use of Multi-threading is allowing your user to interfere with a running job by hitting the cancel button. Here is a VB.NET example that you can use as a template for your projects that will support Multi threading.
On this project, a separate thread is use to process a job. The main screen will remain responsive and will allow the user to abort the job anytime.
1. To support MultiThreading you need to include the following namespace on your project.
Imports System.Threading
2. Create a function that will display the activity on a textbox.
Private Sub WriteLog(ByVal msg As String, ByVal iColor As Color)
logcount = logcount + 1
txtLogs.SelectionColor = iColor
txtLogs.AppendText(vbNewLine + "[" + DateTime.Now.ToString() + "] " + msg)
If Not txtLogs.Focused Then txtLogs.Focus()
End Sub
3. Define a delegate function for the WriteLog.
Delegate Sub SetLogCallback(ByVal msg As String, ByVal icolor As Color)
*A delegate can be defined as a type safe function pointer. It encapsulates the memory address of a function in your code.
4. Now create the thread function to call WriteLog. This function will be called from the Job thread.
Private Sub ThreadWriteLog(ByVal msg As String, ByVal icolor As Color)
logcount = logcount + 1
If Me.txtLogs.InvokeRequired Then
Dim d As New SetLogCallback(AddressOf ThreadWriteLog)
Me.Invoke(d, New Object() {vbNewLine + "[" + DateTime.Now.ToString() + "] " + msg, icolor})
Else
txtLogs.SelectionColor = icolor
txtLogs.AppendText(vbNewLine + "[" + DateTime.Now.ToString() + "] " + msg)
If (Not txtLogs.Focused) Then txtLogs.Focus()
End If
End Sub
5. Now here is the function for the Job Thread.
Private Sub RunJobThread()
ThreadWriteLog("Message from the Job Thread", Color.Black)
End Sub
6. To call the start the Job thread, use the following code.
WriteLog("Starting new thread job for verification process...", Color.Blue)
parsejob = New Thread(New ThreadStart(AddressOf RunJobThread))
parsejob.Start()
You can also download the complete sample project via [mediafire]
For More Coding Tips & Tricks, subscribe now.
Friday, November 20, 2009




0 comments:
Post a Comment