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 and handling them using anonymous delegates, resulting in the following complete solution:

delegate void WorkStarted(); delegate void WorkProgressing(); delegate int WorkCompleted(); class Worker {   public event WorkStarted Started;   public event WorkProgressing Progressing;   public event WorkCompleted Completed;   public void DoWork() {     Console.WriteLine("Worker: work started");     if( this.Started != null )       this.Started();     Console.WriteLine("Worker: work progressing");     if( this.Progressing != null )       this.Progressing();     Console.WriteLine("Worker: work completed");     if( this.Completed != null ) {       foreach( WorkCompleted wc in this.Completed.GetInvocationList() ) {         WorkCompleted wc2 = wc;         wc.BeginInvoke(delegate(IAsyncResult result) {           int grade = wc2.EndInvoke(result);           Console.WriteLine("Worker grade= {0}", grade);         },         null);       }     }   } } class Boss {   public int WorkCompleted() {     System.Threading.Thread.Sleep(3000);     Console.WriteLine("Better...");     return 5; // 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 pleased with worker's work");     return 7;   }   static void Main() {     Worker peter = new Worker();     Boss boss = new Boss();     peter.Completed += boss.WorkCompleted;     peter.Started += Universe.WorkerStartedWork;     peter.Completed += Universe.WorkerCompletedWork;     peter.DoWork();     Console.WriteLine("Main: worker completed work");   } }


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 had completed. However, Peter was familiar with Chapter 18: Multithreaded User Interfaces, so he understood how to manage such issues when building Windows Forms applications.

And so they all lived happily ever after.

The end.




Windows Forms 2.0 Programming
Windows Forms 2.0 Programming (Microsoft .NET Development Series)
ISBN: 0321267966
EAN: 2147483647
Year: 2006
Pages: 216

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