I little bit confused on the behavior of the async
keyword.
Lets say I have 2 methods,
public async Task DoSomething1()
{
await Task.Run(() =>
{
for(int i = 0; i<3; i++)
{
Console.WriteLine("I m doing something:" + i);
}
});
}
And
public Task DoSomething2()
{
return Task.Run(() =>
{
for(int i = 0; i<3; i++)
{
Console.WriteLine("I m doing something:" + i);
}
});
}
From my understanding both methods are awaitable. But when I write a method that has a Task
return type without the async
keyword I need to return a Task
otherwise the compiler generates an error. Its a common thing that a method should return its type. But when I use it with the async
keyword the compiler generates another error that you can't return a Task
. So what does it mean? I am totally confused here.
If you use await in your code, you are required to use the async keyword on the method. If you use async and want to return an actual type, you can declare that your method returns the type as a generic Task like this Task<int> . Task<TResult> , for an async method that returns a value.
Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler. Starting with C# 7.0, any type that has an accessible GetAwaiter method.
C# Language Async-Await Returning a Task without awaitMethods that perform asynchronous operations don't need to use await if: There is only one asynchronous call inside the method. The asynchronous call is at the end of the method. Catching/handling exception that may happen within the Task is not necessary.
The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
If you use await
in your code, you are required to use the async
keyword on the method.
If you use async
and want to return an actual type, you can return the type as a generic Task like this Task<int>
.
Here are the valid return types for an async
method:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types
Task<TResult>
, for an async method that returns a value. Task
, for an async method that performs an operation but returns no value.void
, for an event handler.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