委托(三)(异步调用与动态加载委托)

来源:互联网 发布:landsat8数据下载 编辑:程序博客网 时间:2024/06/05 14:12

非异步处理时结果/*皮特的故事*/
using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
 public class Class1
 {
 }

 delegate void WorkStarted();
 delegate void WorkProgressing();
 delegate int WorkCompleted();

 class Worker
 {
  //申明三个代理
  //public WorkStarted wsStarted;
  //public WorkProgressing wsProgressing;
  //public WorkCompleted wsCompleted;
  //修改为事件就可以动态加载
  public event WorkStarted wsStarted;
  public event WorkProgressing wsProgressing;
  public event WorkCompleted wsCompleted;

  public void DoWork()
  {
   Console.WriteLine("工作:工作开始");
   if (wsStarted != null)
    wsStarted();

   Console.WriteLine("工作:工作进行中");
   if (wsProgressing != null)
    wsProgressing();

   Console.WriteLine("工作:工作结束!");
   Console.WriteLine("你在等待结果时候可以做自己的事!");
   if (wsCompleted != null)
   {
    //Console.WriteLine("工人工作的得分=" + wsCompleted());
    //通过轮询监听者来获取所有请求,否则只能看到最后一个
    foreach (WorkCompleted wc in wsCompleted.GetInvocationList())
    {
     #region 非异步做法
     IAsyncResult res = wc.BeginInvoke(null, null);
     while (!res.IsCompleted)
     {
      System.Threading.Thread.Sleep(1);
      Console.WriteLine("工人工作的得分=" + wc.EndInvoke(res));
     }
     #endregion

     #region 异步工作的
     //想在等待过程中可以做自己的事,但是必须跟这个进程是不同进程的工作,否则会乱套
     //wc.BeginInvoke(new AsyncCallback(WorkGraded), wc);
     #endregion
    }
   }
  }

  private void WorkGraded(IAsyncResult Ares)
  {
   WorkCompleted wc = (WorkCompleted)Ares.AsyncState;
   Console.WriteLine("工人工作的得分=" + wc.EndInvoke(Ares));
  }

 }

 class Boss
 {
  public int WorkCompleted()
  {
   //因为老板需要处理其他事情
   System.Threading.Thread.Sleep(3000);

 


   Console.WriteLine("Better...");
   return 4;
  }

 }

 class Universe
 {
  static void WorkStartedWork()
  {
   Console.WriteLine("Universe notices Worker Starting Work!");
  }

  static int WorkCompleteWork()
  {
   //中断处理其他事情
   System.Threading.Thread.Sleep(4000);

   Console.WriteLine("Universe pleased with Work's Work!");
   return 7;
  }
  static void Main()
  {
   Worker wPerter = new Worker();
   Boss bBoss = new Boss();
   wPerter.wsCompleted += new WorkCompleted(bBoss.WorkCompleted);
   wPerter.wsStarted += new WorkStarted(Universe.WorkStartedWork);
   wPerter.wsCompleted +=new WorkCompleted(Universe.WorkCompleteWork);

   wPerter.DoWork();
   Console.WriteLine("Main:工人工作完成!");
   Console.ReadLine();

  }
 }
}
 以上是异步处理的结果

接着是非异步处理结果的图片

非异步处理的结果

原创粉丝点击