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

gre*_*gkb 9 c# notifications delegates

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


SomeMethod { // Member of AClass{}
    DoSomething;
    Start WorkerMethod() from BClass in another thread;
    DoSomethingElse;
}
Run Code Online (Sandbox Code Playgroud)

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


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

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

Isa*_*avo 13

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

简而言之,你做到:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate { myBClass.DoHardWork(); }
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);
worker.RunWorkerAsync();
Run Code Online (Sandbox Code Playgroud)

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


Kei*_*ith 5

在.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();
Run Code Online (Sandbox Code Playgroud)

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