Calling a method asynchronously [closed]
I have a method named X()
. I need to call that method asynchronously. Can anyone give sample code for this?
There are a couple of ways, involving threads and delegates. Here's one example using the thread pool:
ThreadPool.QueueUserWorkItem(state => { X(); });
And here's one involving delegates:
Func<string> del = X;
del.BeginInvoke(ar =>
{
Func<string> endDel = (Func<string>)ar.AsyncState;
var result = endDel.EndInvoke(ar);
Console.WriteLine(result);
}, del);
If your really lost on threading with C#, the BackgroundWorker is a good place to start. It handles a simple DoWork method to run your asynchronis calls and an OnComplete event to do any UI manipulation when the thread returns.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
精彩评论