委派任务并在完成时收到通知(在 C# 中)
-
09-06-2019 - |
题
从概念上讲,我想完成以下任务,但无法理解如何在 C# 中正确编码:
SomeMethod { // Member of AClass{}
DoSomething;
Start WorkerMethod() from BClass in another thread;
DoSomethingElse;
}
然后,当 WorkerMethod() 完成时,运行以下命令:
void SomeOtherMethod() // Also member of AClass{}
{ ... }
谁能举个例子吗?
解决方案
这 后台工作者 为此,.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
方法。
警告 :不要忘记随时打电话 EndInvoke
于 IAsyncResult
以避免最终的内存泄漏,如中所述 本文.
查看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,并在另一个线程上将该方法排队。然后,当 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.
}
}
不隶属于 StackOverflow