如何在c#中异步调用任何方法

Tho*_*mas 102 c# asynchronous

有人可以给我看一小段代码,演示如何在c#中异步调用方法吗?

Dre*_*fer 124

如果使用action.BeginInvoke(),则必须在某处调用EndInvoke - 否则框架必须在堆上保存异步调用的结果,从而导致内存泄漏.

如果您不想使用async/await关键字跳转到C#5,您可以使用.Net 4中的Task Parallels库.它比使用BeginInvoke/EndInvoke更好,并且提供了一种干净的方式来触发 - 并忘记异步工作:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();
Run Code Online (Sandbox Code Playgroud)

如果您有调用参数的方法,则可以使用lambda来简化调用,而无需创建委托:

void Foo2(int x, string y)
{
    return;
}
...
new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();
Run Code Online (Sandbox Code Playgroud)

我很确定(但可以肯定的是不是肯定的)C#5 async/await语法只是Task库周围的语法糖.

  • 如果还不是很清楚,最后的假设是:async/await是正确的,但它将极大地改变代码的外观. (2认同)

ms0*_*007 48

从.Net 4.5开始,您可以使用Task.Run简单地启动操作:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));
Run Code Online (Sandbox Code Playgroud)

http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx


Tho*_*que 24

这是一种方法:

// The method to call
void Foo()
{
}


Action action = Foo;
action.BeginInvoke(ar => action.EndInvoke(ar), null);
Run Code Online (Sandbox Code Playgroud)

当然Action,如果方法具有不同的签名,则需要替换为其他类型的委托


Mic*_*ake 5

查看 MSDN 文章使用 Async 和 Await 进行异步编程,如果您有能力尝试新东西。它已添加到 .NET 4.5。

链接中的示例代码片段(它本身来自这个 MSDN 示例代码项目):

// Three things to note in the signature: 
//  - The method has an async modifier.  
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer. 
//  - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}
Run Code Online (Sandbox Code Playgroud)

引用:

如果AccessTheWebAsync在调用 GetStringAsync 和等待其完成之间没有任何可以做的工作,您可以通过在以下单个语句中调用和等待来简化代码。

string urlContents = await client.GetStringAsync();
Run Code Online (Sandbox Code Playgroud)

更多细节在链接中