Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

A Practical Use of the MVC Pattern

, 8 Jan 2007
Another approach to the MVC pattern
// � 2006 IDesign Inc. All rights reserved 
//Questions? Comments? go to 
//http://www.idesign.net

using System;
using System.Drawing;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging;
using System.Runtime.CompilerServices;

namespace WinFormsEx
{
   [ToolboxBitmap(typeof(BackgroundWorker),"bw.bmp")]
   public class BackgroundWorker : Component
   {
      bool m_CancelPending = false;
      bool m_ReportsProgress = false;
      bool m_SupportsCancellation = false;
      public event DoWorkEventHandler DoWork;
      public event ProgressChangedEventHandler ProgressChanged;
      public event RunWorkerCompletedEventHandler RunWorkerCompleted;


      public bool WorkerSupportsCancellation
      {
         get
         {
            lock(this)
            {
               return m_SupportsCancellation;
            }
         }

         set
         {
            lock(this)
            {
               m_SupportsCancellation = value;
            }
         }
      }
      public bool WorkerReportsProgress
      {
         get
         {
            lock(this)
            {
               return m_ReportsProgress;
            }
         }

         set
         {
            lock(this)
            {
               m_ReportsProgress = value;
            }
         }
      } 
      [MethodImpl(MethodImplOptions.NoInlining)]
      void ProcessDelegate(Delegate del,params object[] args)
      {
         if(del == null)
         {
            return;
         }
         Delegate[] delegates = del.GetInvocationList();
         foreach(Delegate handler in delegates)
         {
            InvokeDelegate(handler,args);
         }
      }
      void InvokeDelegate(Delegate deleg,params object[] args)
      {
         ISynchronizeInvoke synchronizer  = deleg.Target as ISynchronizeInvoke;
		  if ( synchronizer != null ) 
		  {
			  // mostly a windows forms object or an object that implements 
			  // ISynchronizeInvoke
			  if ( synchronizer.InvokeRequired == false ) 
			  {
				  try 
				  {
					  deleg.DynamicInvoke(args);
				  }
				  catch ( Exception exc ) 
				  {
					  if ( deleg.Target != null ) 
						  Trace.WriteLine(
							  "InvokeDelegate: " + deleg.Target.ToString() + " - " + 
							  exc.Message);
					  else 
						  Trace.WriteLine(
							  "InvokeDelegate: " + exc.Message);
				  }
				  return;
			  }
			  else 
			  {
				  try 
				  {
					  synchronizer.Invoke(deleg, args);
				  }
				  catch ( Exception exc ) 
				  {
					  if ( deleg.Target != null ) 
						  Trace.WriteLine(
							  "InvokeDelegate: " + deleg.Target.ToString() + " - " + 
							  exc.Message);
					  else 
						  Trace.WriteLine(
							  "InvokeDelegate: " + exc.Message);
				  }
			  }
		  }
		  else 
		  {
			  try 
			  {
				  deleg.DynamicInvoke(args);
			  }
			  catch ( Exception exc ) 
			  {
				  if ( deleg.Target != null ) 
					  Trace.WriteLine(
						  "InvokeDelegate: " + deleg.Target.ToString() + " - " + 
						  exc.Message);
				  else 
					  Trace.WriteLine(
						  "InvokeDelegate: " + exc.Message);
			  }
		  }
	  }

      void ReportCompletion(IAsyncResult asyncResult)
      {
         AsyncResult ar = (AsyncResult)asyncResult;
         DoWorkEventHandler del  = (DoWorkEventHandler)ar.AsyncDelegate;
         
         DoWorkEventArgs doWorkArgs = (DoWorkEventArgs)asyncResult.AsyncState;
         object result = null;
         Exception error = null;
         try
         {
            del.EndInvoke(asyncResult);
            result = doWorkArgs.Result;
         }
         catch(Exception exception)
         {
            error = exception;
         }

         RunWorkerCompletedEventArgs completedArgs = new RunWorkerCompletedEventArgs(result,error,doWorkArgs.Cancel);
         ProcessDelegate(RunWorkerCompleted,this,completedArgs);
      }

      public void RunWorkerAsync()
      {
         RunWorkerAsync(null);
      }

      public void RunWorkerAsync(object argument)
      {
         RunWorkerAsync(DoWork,argument);
      }
      [MethodImpl(MethodImplOptions.NoInlining)]
      void RunWorkerAsync(DoWorkEventHandler doWork,object argument)
      {
         m_CancelPending = false;
         if(doWork != null)
         {
            DoWorkEventArgs args = new DoWorkEventArgs(argument);
            AsyncCallback callback = new  AsyncCallback(ReportCompletion);
            doWork.BeginInvoke(this,args,callback,args);
         }
      }

      public void ReportProgress(int percent)
      {
         ProgressChangedEventArgs progressArgs = new ProgressChangedEventArgs(percent);
         ProcessDelegate(ProgressChanged,this,progressArgs);
      }
      public void CancelAsync()
      {
         lock(this)
         {
            m_CancelPending = true;
         }
      }
      public bool CancellationPending
      {
         get
         {
            lock(this)
            {
               return m_CancelPending;
            }
         }
      }
   } 
}

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)

About the Author

Zoltan Balazs
Software Developer
Romania Romania
I've did some programming for Macintosh a few years back and working with Microsoft technologies since then.

| Advertise | Privacy | Mobile
Web04 | 2.8.140718.1 | Last Updated 8 Jan 2007
Article Copyright 2007 by Zoltan Balazs
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid