从概念上讲,我想完成以下操作,但却无法理解如何在C#中正确编码:
SomeMethod { // Member of AClass{}
DoSomething;
Start WorkerMethod() from BClass in another thread;
DoSomethingElse;
}
然后,当WorkerMethod()完成时,运行:
void SomeOtherMethod() // Also member of AClass{}
{ ... }
任何人都可以举一个例子吗?
答案 0 :(得分:13)
为了这个目的,BackgroundWorker类被添加到.NET 2.0中。
简而言之,你这样做:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate { myBClass.DoHardWork(); }
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);
worker.RunWorkerAsync();
如果您愿意,还可以添加取消和进度报告等精彩内容:)
答案 1 :(得分: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();
在.Net 1中,您必须使用线程。
答案 2 :(得分:2)
您必须使用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();
}
}
答案 3 :(得分:2)
虽然这里有几种可能性,但我会使用一个委托,使用BeginInvoke
方法异步调用。
警告:请不要忘记始终致电EndInvoke
上的IAsyncResult
以避免最终的内存泄漏,如this article中所述。
答案 4 :(得分:1)
查看BackgroundWorker。
答案 5 :(得分:1)
使用异步代理:
// 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
答案 6 :(得分:0)
好的,我不确定你想怎么做。在您的示例中,看起来WorkerMethod不会创建自己的线程来执行,但您想在另一个线程上调用该方法。
在这种情况下,创建一个调用WorkerMethod的short worker方法,然后调用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.
}
}