Click here to Skip to main content
15,892,072 members
Articles / Desktop Programming / Windows Forms

AsyncWorker - A Typesafe BackgroundWorker (and about Threading in General)

Rate me:
Please Sign up or sign in to vote.
4.76/5 (23 votes)
11 Apr 2010CPOL9 min read 58.4K   1.8K   93  
Generic methods enable typesafe Threading
Imports System.Drawing
Imports System.Windows.Forms

Partial Public Class uclAsyncWorker : Inherits UserControl

   Private WithEvents _Worker As New AsyncWorker()

   Public Sub New()
      InitializeComponent()
      UpdateGui()
   End Sub

   Private Sub _Worker_IsRunningChanged(ByVal sender As Object, ByVal e As EventArgs) _
         Handles _Worker.IsRunningChanged
      UpdateGui()
   End Sub

   Private Sub UpdateGui()
      btCancel.Visible = _Worker.IsRunning
      progressBar1.Visible = _Worker.IsRunning
      If _Worker.IsRunning Then
         RemoveHandler Me.MouseDown, AddressOf ucl_MouseDown
         progressBar1.Value = 0
      Else
         AddHandler Me.MouseDown, AddressOf ucl_MouseDown
      End If
   End Sub

   Private Sub ucl_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
      _Worker.RunAsync(AddressOf EvaluateData, DateTime.Now, e.Location)
   End Sub

   Private Sub EvaluateData(ByVal t As DateTime, ByVal p As Point)
      For i = 0 To 299
         Threading.Thread.Sleep(10)
         'reports a progress only if the previous report was more than 0.3s ago
         If Not _Worker.ReportProgress(AddressOf ReportProgress, i \ 3) Then Return
      Next
      Dim s = String.Format("Position {0} / {1}" & vbLf & "clicked at {2:T}", p.X, p.Y, t)
      _Worker.NotifyGui(AddressOf DisplayResult, s, p)
   End Sub

   Private Sub ReportProgress(ByVal value As Integer)
      progressBar1.Value = value
   End Sub

   Private Sub DisplayResult(ByVal s As String, ByVal p As Point)
      label1.Text = s
      label1.Location = p - label1.Size
   End Sub

   Private Sub btCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btCancel.Click
      _Worker.Cancel()
      label1.Text = "Canceled"
   End Sub

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions