Click here to Skip to main content
15,892,480 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
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

namespace AsyncWorkerCs {
   public partial class uclBgwSimple : UserControl {

      public uclBgwSimple() { InitializeComponent(); }

      struct Data2Thread {
         public DateTime Time;
         public Point Pt;
      }
      struct Data2Gui {
         public string Text;
         public Point Pt;
      }

      private void ucl_MouseDown(object sender, MouseEventArgs e) {
         if(backgroundWorker1.IsBusy) {
            MessageBox.Show("backgroundWorker1.IsBusy");
            return;
         }
         Data2Thread d = new Data2Thread() { Time = DateTime.Now, Pt = e.Location };
         backgroundWorker1.RunWorkerAsync(d);
      }

      private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
         Data2Thread d = (Data2Thread)e.Argument;           
         System.Threading.Thread.Sleep(1000);
         Data2Gui d2g = new Data2Gui() {
            Pt = d.Pt,
            Text = string.Format("Position {0} / {1}\nclicked at {2:T}", d.Pt.X, d.Pt.Y, d.Time)
         };
         e.Result = d2g;
      }

      private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
         Data2Gui d2g = (Data2Gui)e.Result;
         label1.Text = d2g.Text;
         label1.Location = d2g.Pt - label1.Size;
      }

   }
}

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