Thursday, August 25, 2005

Threding Pattern Template

Below is the code listing I use as a template when I want to handle basic multi-threading.
The Template uses the following Pattern:
  • BeginProcess
  • Process
  • EndProcess
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

/// <summary>
/// Represents a threading template class.
/// </summary>
public class ThreadProcessor : System.Windows.Forms.Form
{
    private System.Threading.Thread processingThread;
    
    // 
    // Note: Windows Form Designer generated code has been removed 
    // to simplify this example.
    // 
    
    /// <summary>
    /// Begins the Thread process.
    /// </summary>
    private void BeginProcess()
    {
        // Check if the thread is currently processiing.
        if (this.IsBusy)
        {
            // You could display a message here.
            this.CancelProcessing();
        }
        
        // Execute CopyColumns().
        this.processingThread = new Thread(new ThreadStart(this.Process));
        this.processingThread.IsBackground = true;
        this.processingThread.Start();
        
    }
    
    /// <summary>
    /// The method that does the work.
    /// </summary>
    private void Process()
    {
        try
        {
            // TODO: Add processing logic here.
        }
        catch (ThreadAbortException)
        {
            // This catch allows EndProcess() to be 
            // called even if the thread is aborted.
            // TODO: Optionally add cancel logic here.
        }
        finally
        {
            // TODO: Optionally add cleanup logic here.
            
            // Invoke EndProcess() on the Form's thread.
            Delegate endDelegate = new EndProcessDelegate(this.EndProcess);
            this.BeginInvoke(endDelegate);
        }
    }
    
    /// <summary>
    /// Aborts the processing thread.
    /// </summary>
    private void CancelProcess()
    {
        if (this.IsBusy)
        {
            this.processingThread.Abort();
        }
    }
    
    /// <summary>
    /// Completes the Thread process.
    /// </summary>
    private void EndProcess()
    {
        // TODO: Add end process logic here.
    }
        
    /// <summary>
    /// Returns true if the processingThread is active.
    /// </summary>
    public bool IsBusy
    {
        get {return (this.processingThread != null && this.processingThread.IsAlive);}
    }
}

/// <summary>
/// Represents the EndProcess method.
/// </summary>
public delegate void EndProcessDelegate();



2 comments:

Billy said...

.NET 2.0 it is easier to use the BackgroundWorker component.

Billy said...

.NET 2.0 it is easier to use the BackgroundWorker component.