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

从概念上讲,我想完成以下操作,但却无法理解如何在C#中正确编码:

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

然后,当WorkerMethod()完成时,运行以下命令:

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

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

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

简而言之,你做到:

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

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

在.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中,您必须使用线程。

您必须使用AsyncCallBacks。 您可以使用AsyncCallBacks指定方法的委托,然后指定在目标方法执行完成后调用的CallBack方法。

这是一个小例子,运行并亲自看看。

课程{

  public delegate void AsyncMethodCaller(); public static void WorkerMethod() { Console.WriteLine("I am the first method that is called."); Thread.Sleep(5000); Console.WriteLine("Exiting from WorkerMethod."); } public static void SomeOtherMethod(IAsyncResult result) { Console.WriteLine("I am called after the Worker Method completes."); } static void Main(string[] args) { AsyncMethodCaller asyncCaller = new AsyncMethodCaller(WorkerMethod); AsyncCallback callBack = new AsyncCallback(SomeOtherMethod); IAsyncResult result = asyncCaller.BeginInvoke(callBack, null); Console.WriteLine("Worker method has been called."); Console.WriteLine("Waiting for all invocations to complete."); Console.Read(); } } 

虽然这里有几种可能性,但我会使用一个委托,使用BeginInvoke方法异步调用。

警告 :不要忘记始终在IAsyncResult上调用EndInvoke以避免最终的内存泄漏,如本文所述 。

查看BackgroundWorker。

使用异步委托:

 // Method that does the real work public int SomeMethod(int someInput) { Thread.Sleep(20); Console.WriteLine(”Processed input : {0}”,someInput); return someInput+1; } // Method that will be called after work is complete public void EndSomeOtherMethod(IAsyncResult result) { SomeMethodDelegate myDelegate = result.AsyncState as SomeMethodDelegate; // obtain the result int resultVal = myDelegate.EndInvoke(result); Console.WriteLine(”Returned output : {0}”,resultVal); } // Define a delegate delegate int SomeMethodDelegate(int someInput); SomeMethodDelegate someMethodDelegate = SomeMethod; // Call the method that does the real work // Give the method name that must be called once the work is completed. someMethodDelegate.BeginInvoke(10, // Input parameter to SomeMethod() EndSomeOtherMethod, // Callback Method someMethodDelegate); // AsyncState 

好吧,我不确定你想怎么做。 从您的示例中,看起来WorkerMethod不会创建自己的线程来执行,但您想在另一个线程上调用该方法。

在这种情况下,创建一个调用WorkerMethod然后调用SomeOtherMethod的short worker方法,并在另一个线程上将该方法排队。 然后当WorkerMethod完成时,调用SomeOtherMethod。 例如:

 public class AClass { public void SomeMethod() { DoSomething(); ThreadPool.QueueUserWorkItem(delegate(object state) { BClass.WorkerMethod(); SomeOtherMethod(); }); DoSomethingElse(); } private void SomeOtherMethod() { // handle the fact that WorkerMethod has completed. // Note that this is called on the Worker Thread, not // the main thread. } }