Happiness in the Universe


Peter, his boss, and the universe were finally satisfied. Peter's boss and the universe were allowed to be notified of the events that interested them, reducing the burden of implementation and the cost of unnecessary round-trips. Peter could notify each of them, ignoring how long it took them to return from their target methods while still getting his results asynchronously. The result was the following complete solution:

 delegate void WorkStarted(); delegate void WorkProgressing(); delegate int WorkCompleted(); class Worker {   public void DoWork() {     Console.WriteLine("Worker: work started");     if( started != null ) started();     Console.WriteLine("Worker: work progressing");     if( progressing != null ) progressing();     Console.WriteLine("Worker: work completed");     if( completed != null ) {       foreach( WorkCompleted wc in completed.GetInvocationList() ) {         wc.BeginInvoke(new AsyncCallback(WorkGraded), wc);       }     }   }   void WorkGraded(IAsyncResult res) {     WorkCompleted wc = (WorkCompleted)res.AsyncState;     int grade = wc.EndInvoke(res);     Console.WriteLine("Worker grade= " + grade);   }   public event WorkStarted started;   public event WorkProgressing progressing;   public event WorkCompleted completed; } class Boss {   public int WorkCompleted() {     System.Threading.Thread.Sleep(3000);     Console.WriteLine("Better..."); return 6; /* out of 10 */   } } class Universe {   static void WorkerStartedWork() {     Console.WriteLine("Universe notices worker starting work");   }   static int WorkerCompletedWork() {     System.Threading.Thread.Sleep(4000);     Console.WriteLine("Universe is pleased with worker's work");     return 7;   }   static void Main() {     Worker peter = new Worker();     Boss boss = new Boss();     peter.completed += new WorkCompleted(boss.WorkCompleted);     peter.started += new WorkStarted(Universe.WorkerStartedWork);     peter.completed += new WorkCompleted(Universe.WorkerCompletedWork);     peter.DoWork();     Console.WriteLine("Main: worker completed work");     Console.ReadLine();   } } 

Peter knew that getting results asynchronously came with issues, because as soon as he fired events asynchronously, the target methods were likely to be executed on another thread, as was Peter's notification of when the target method has completed. However, Peter was familiar with Chapter 14: Multithreaded User Interfaces, so he understood how to manage such issues when building WinForms applications.

And they all lived happily ever after. The end.



Windows Forms Programming in C#
Windows Forms Programming in C#
ISBN: 0321116208
EAN: 2147483647
Year: 2003
Pages: 136
Authors: Chris Sells

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net