开发者

Calling a method asynchronously [closed]

开发者 https://www.devze.com 2022-12-19 16:54 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_运维问答 Closed 10 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消