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

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

问题描述

谁能给我看一小段代码来演示如何在 c# 中异步调用方法?

解决方案

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

如果您不想使用 async/await 关键字跳转到 C# 5,您可以使用 .Net 4 中的 Task Parallels 库.它比使用 BeginInvoke/EndInvoke 好得多,并且提供了一种简洁的方式对异步作业一劳永逸:

使用 System.Threading.Tasks;...void Foo(){}...新任务(Foo).Start();

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

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

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

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

解决方案

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.

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();

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();

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天全站免登陆