当前位置:  开发笔记 > 编程语言 > 正文

委派任务并在完成时收到通知(在C#中)

如何解决《委派任务并在完成时收到通知(在C#中)》经验,为你挑选了2个好方法。

从概念上讲,我想完成以下操作,但是在理解如何在C#中正确编码时遇到了问题:

SomeMethod { // Member of AClass{}
    DoSomething;
    Start WorkerMethod() from BClass in another thread;
    DoSomethingElse;
}

然后,当WorkerMethod()完成时,运行:

void SomeOtherMethod()  // Also member of AClass{}
{ ... }

任何人都可以举一个例子吗?



1> Isak Savo..:

为了这个目的,BackgroundWorker类已添加到.NET 2.0中.

简而言之,你做到:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate { myBClass.DoHardWork(); }
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);
worker.RunWorkerAsync();

如果你想要,你还可以添加像取消和进度报告这样的花哨的东西:)



2> Keith..:

在.Net 2中引入了BackgroundWorker,这使得运行异步操作变得非常简单:

BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true };

bw.DoWork += (sender, e) => 
   {
       //what happens here must not touch the form
       //as it's in a different thread
   };

bw.ProgressChanged += ( sender, e ) =>
   {
       //update progress bars here
   };

bw.RunWorkerCompleted += (sender, e) => 
   {
       //now you're back in the UI thread you can update the form
       //remember to dispose of bw now
   };

worker.RunWorkerAsync();

在.Net 1中,您必须使用线程.

推荐阅读
虎仔球妈_459
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有