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

namespace AsyncWorkerCs {
   public partial class uclExceptions : UserControl {

      private Action<string> _ThrowEx = delegate(string text) { throw new Exception(text); }; 

      public uclExceptions() {         InitializeComponent();      }

      private void btBackgroundworker_Click(object sender, EventArgs e) {
         backgroundWorker1.RunWorkerAsync();
      }

      private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
         _ThrowEx("thrown by  backgroundWorker1"); 
      }

      private void btWithoutEndInvoke_Click(object sender, EventArgs e) {
         _ThrowEx.BeginInvoke("thrown without EndInvoke", null, null);
      }

      private void btWithEndInvoke_Click(object sender, EventArgs e) {
         _ThrowEx.BeginInvoke("thrown with EndInvoke", _ThrowEx.EndInvoke, null);
      }

      private void btAsyncworker_Click(object sender, EventArgs e) {
         _ThrowEx.RunAsync("thrown by Asyncworker"); 
      }

      private void btSynchron_Click(object sender, EventArgs e) {
         _ThrowEx("thrown in main-thread"); 
      }
   }
}

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