Click here to Skip to main content
15,891,316 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;

namespace AsyncWorkerCs {
   public partial class uclAsyncWorker : UserControl {
      
      private AsyncWorker _Worker = new AsyncWorker();
      
      public uclAsyncWorker() {
         InitializeComponent();
         _Worker.IsRunningChanged += (s, e) => UpdateGui();
         UpdateGui();
      }
      
      private void UpdateGui() {
         btCancel.Visible = progressBar1.Visible = _Worker.IsRunning;
         if(_Worker.IsRunning) {
            this.MouseDown -= ucl_MouseDown;
            progressBar1.Value = 0;
         } else { this.MouseDown += ucl_MouseDown; }
      }
      
      void ucl_MouseDown(object sender, MouseEventArgs e) {
         _Worker.RunAsync(EvaluateData, DateTime.Now, e.Location);
      }
      
      private void EvaluateData(DateTime t, Point p) {
         for(var i = 0; i < 300; i++) {
            System.Threading.Thread.Sleep(10);
            //reports a progress only if the previous one was more than 0.3s ago
            //ReportProgress()==false indicates the process is canceled.
            if(!_Worker.ReportProgress(() => progressBar1.Value = i / 3))return;
         }
         var s = string.Format("Position {0} / {1}\nclicked at {2:T}", p.X, p.Y, t);
         _Worker.NotifyGui(DisplayResult, s, p);
      }
      
      private void DisplayResult(string s, Point p) {
         label1.Text = s;
         label1.Location = p - label1.Size;
      }
      
      private void btCancel_Click(object sender, EventArgs e) {
         _Worker.Cancel();
         label1.Text = "Canceled";
      }
 
   }
}

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