如何调用在C#异步的任何方法 [英] How to call any method asynchronously in c#

查看:98
本文介绍了如何调用在C#异步的任何方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能有人请告诉我code的一个小片段演示如何异步调用的方法在C#中?

Could someone please show me a small snippet of code which demonstrates how to call a method asynchronously in c#?

推荐答案

如果您使用action.BeginInvoke(),您have要调用EndInvoke 地方 - 否则框架必须持有堆的异步调用的结果,导致内存泄漏

If you use action.BeginInvoke(), you have to call EndInvoke somewhere - else the framework has to hold the result of the async call on the heap, resulting in a memory leak.

如果你不希望跳转到C#5的异步/等待的关键字,你可以使用.NET 4的任务的Parallels库它的很多,比使用的BeginInvoke / EndInvoke会更好了,并给出了一个干净的方式对于异步作业,发射后不管:

If you don't want to jump to C# 5 with the async/await keywords, you can just use the Task Parallels library in .Net 4. It's much, much nicer than using BeginInvoke/EndInvoke, and gives a clean way to fire-and-forget for async jobs:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

如果你有方法来调用带参数,你可以使用lambda简化呼叫,而无需创建代表:

If you have methods to call that take parameters, you can use a lambda to simplify the call without having to create delegates:

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

我确信(但无可否认不积极)是pretty,在C#5异步/等待语法是围绕着任务库只是语法糖。

I'm pretty sure (but admittedly not positive) that the C# 5 async/await syntax is just syntactic sugar around the Task library.

这篇关于如何调用在C#异步的任何方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆