Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the different between an async delegate and async method?

Tags:

c#

What's the different between an async delegate and async method?

Someone told me they were different in C#, but I thought they were the same thing.

like image 520
DayOne Avatar asked May 19 '10 09:05

DayOne


2 Answers

Delegates first. When you declare one, the compiler automatically generates three methods for the delegate type:

  • Invoke(...), taking the same arguments as the delegate declaration
  • BeginInvoke(..., AsyncCallback, object) where ... are the declared arguments
  • EndInvoke(IAsyncResult)

The Invoke() method calls the delegate target synchronously, just like a plain call. The BeginInvoke() method is the asynchronous call, the target method runs on a thread-pool thread. The EndInvoke() call is required after the method completes to release resources allocated for the call and to re-raise any exception that might have aborted the call.

The .NET framework contains many classes that have a BeginXxxx() method. The MSDN Library refers to them as asynchronous operations, not asynchronous methods. They start an operation that completes asynchronously.

Starting with .NET 4.5 and supported by C# version 5, the asynchronous operations whose name end in Async and return a Task can be called in an await expression. When used in a method that has the async modifier. This greatly simplifies dealing with asynchronous operations, important in WinRT where many common operations are asynchronous.

like image 180
Hans Passant Avatar answered Sep 19 '22 15:09

Hans Passant


For the differences, as well as some further discussion, see Asynchronous methods and asynchronous delegates right here on SO.

like image 27
mdb Avatar answered Sep 20 '22 15:09

mdb