In one of MVA videos i saw next construction:
static void Main(string[] args) { Action testAction = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("After first delay"); await Task.Delay(100); Console.WriteLine("After second delay"); }; testAction.Invoke(); }
Result of execution will be:
In Press any key to continue . . .
It's perfectly compiles, but right now i don't see any way to await it. I might put Thread.Sleep
or Console.ReadKey
after invocation, but that's not what i want.
So how this delegate should be modified to become awaitable?(or at least how can i track that execution completed?)
Is there are any practical usage of such delegates?
Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller.
Create the delegate and matching procedures Create a delegate named MySubDelegate . Declare a class that contains a method with the same signature as the delegate. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling the built-in Invoke method.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.
The AsyncCallback delegate represents a callback method that is called when the asynchronous operation completes. The callback method takes an IAsyncResult parameter, which is subsequently used to obtain the results of the asynchronous operation.
In order for something to be awaited, it has to be awaitable. As void
is not so, you cannot await on any Action
delegate.
An awaitable is any type that implements a GetAwaiter
method, which returns a type that implements either INotifyCompletion
or ICriticalNotifyCompletion
, like Task
and Task<T>
, for example.
If you want to wait on a delegate, use Func<Task>
, which is an equivalent to a named method with the following signature:
public Task Func()
So, in order to await, change your method to:
static void Main(string[] args) { Func<Task> testFunc = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("First delay"); await Task.Delay(100); Console.WriteLine("Second delay"); }; }
And now you can await it:
await testFunc();
"Async void is for top-level event-handlers only",
http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-1-Async-void-is-for-top-level-event-handlers-only
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With