网站导航免费论文 原创论文 论文搜索 原创论文 网学软件 学术大家 资料中心 会员中心 问题解答 原创论文 论文素材 设计下载 最新论文 下载排行 论文上传 在线投稿 联系我们
返回网学首页
网学联系
最新论文 推荐专题 热门论文 素材专题
当前位置: 网学 > 编程文档 > C# > 正文
形象解说C#委托和事件
来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 12/10/14
下载{$ArticleTitle}原创论文样式
iverse都可以仅被通知其感兴趣的事件,并减少了实现的负担和不必要的来回调用。Peter可以通知他们每一个人,而不必管需要多长时间才能从那些目标方法中返回,并仍然可以异步得到评分结果。结果得到如下完整的解决方案:

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; /* 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知道异步获取结果会带来一些问题。由于异步触发事件,所以目标方法有可能执行于另一个线程中,就像Peter的“目标方法何时完成”的通知那样。然而,Peter熟悉第14章“多线程用户界面”,因此,他知道在构建WinForms应用程序时如何去处理此类问题。

从此,他们一直过得都很快乐。

 

网学推荐

免费论文

原创论文

浏览:
设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号