Click here to Skip to main content
15,885,067 members
Articles / Desktop Programming / Windows Forms

A Practical Use of the MVC Pattern

Rate me:
Please Sign up or sign in to vote.
4.55/5 (41 votes)
8 Jan 2007CPOL5 min read 179.1K   2.7K   145  
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)


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

Comments and Discussions