Home > Blockchain >  Is async()=>await funcAsync() equivalent to ()=>funcAsync() in C#?
Is async()=>await funcAsync() equivalent to ()=>funcAsync() in C#?

Time:04-05

In the GetOrCreateAsync of learning asp.net core memoryCache, a Func<ICacheEntry, Task> parameter is required, and then I see the sample code as

GetOrCreateAsync("allInfo", async e=> await _service.GetAllAsync())

I changed it to

GetOrCreateAsync("allInfo", e=>_service.GetAllAsync())

can also run normally, so I want to know if the two are equivalent, and if they are different, what is the difference?

CodePudding user response:

I want to know if the two are equivalent, and if they are different

Yes, They are different.

This one will create a method for Func<ICacheEntry, Task>

e=>_service.GetAllAsync()

but async ... await will create a state machine code which means the method could be awaitable automatically.

async e=> await _service.GetAllAsync()

Here is a sample code, Although this code looks a little stupid but I want to show the different part of code.

Action s = ()=>  Task.Delay(100);

code of normal delegate

Action s = async ()=> await Task.Delay(100);

code of async delegate

  •  Tags:  
  • c#
  • Related