Home > database >  Use the async modifier to prefix a delegate
Use the async modifier to prefix a delegate

Time:08-31

In the book Microsoft Visual C# Step by Step says in chapter 24:

Tip You can use the async modifier to prefix a delegate, making it possible to create delegates that incorporate asynchronous processing by using the await operator.

I'm trying to declare a delegate with the async modifier and the code doesn't compile, what am I doing wrong? Or I misunderstand the author. How to declare an asynchronous delegate?

async delegate Task MyDelegate();

CodePudding user response:

You cannot use async with delegate types, but you can with the delegates themselves. E.g., using the more modern lambda syntax: var d = async () => await Task.Yield();

CodePudding user response:

I think what the author means is something like this

MyDelegate d = 
    async () => await Task.Delay(1000); //delegate with async prefix

await d();

with a delegate definition like so: delegate Task MyDelegate();

  • Related