Click here to Skip to main content
15,895,011 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.5K   1.8K   93  
Generic methods enable typesafe Threading
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel

Partial Public Class uclBgwSimple : Inherits UserControl

   Private Structure Data2Thread
      Public Time As DateTime
      Public Pt As Point
   End Structure
   Private Structure Data2Gui
      Public Text As String
      Public Pt As Point
   End Structure

   Private Sub ucl_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Me.MouseDown
      If BackgroundWorker1.IsBusy Then
         MessageBox.Show("backgroundWorker1.IsBusy")
         Return
      End If
      Dim d As New Data2Thread() With {.Time = DateTime.Now, .Pt = e.Location}
      BackgroundWorker1.RunWorkerAsync(d)
   End Sub

   Private Sub backgroundWorker1_DoWork( _
         ByVal sender As Object, ByVal e As DoWorkEventArgs) _
         Handles BackgroundWorker1.DoWork
      Dim d As Data2Thread = CType(e.Argument, Data2Thread)
      System.Threading.Thread.Sleep(1000)
      Dim d2g As New Data2Gui() With { _
       .Pt = d.Pt, _
       .Text = String.Format("Position {0} / {1}" & vbLf & "clicked at {2:T}", d.Pt.X, d.Pt.Y, d.Time) _
      }
      e.Result = d2g
   End Sub

   Private Sub backgroundWorker1_RunWorkerCompleted( _
         ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
         Handles BackgroundWorker1.RunWorkerCompleted
      Dim d2g As Data2Gui = CType(e.Result, Data2Gui)
      label1.Text = d2g.Text
      label1.Location = d2g.Pt - label1.Size
   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