Could someone please show me a small snippet of code which demonstrates how to call a method asynchronously in c#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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:
If you have methods to call that take parameters, you can use a lambda to simplify the call without having to create delegates:
I'm pretty sure (but admittedly not positive) that the C# 5 async/await syntax is just syntactic sugar around the Task library.
Here's a way to do it:
Of course you need to replace
Action
by another type of delegate if the method has a different signatureCheck out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.
Example code snippet from the link (which is itself from this MSDN sample code project):
Quoting:
More details are in the link.
Starting with .Net 4.5 you can use Task.Run to simply start an action:
http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx