谁能给我看一小段代码来演示如何在 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#中异步调用任何方法
发布评论