I would like to know if the following code will wait for the async method to complete before executing the main thread or will just continue the main thread if condition and consider the method return as false.
public async Task<bool> SomeMethod
{
if(await AsyncMethod(param))
{
//Do something
}
}
...
And the async method is defined as:
public async Task<bool> AsyncMethod(SomeClass param)
{
//Do something
}
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
Async methods can have the following return types: 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.
Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.
I would like to know if the following code will wait for the async method to complete before executing the main thread or will just continue the main thread if condition and consider the method return as false.
Neither.
await
is an "asynchronous wait". In other words, the method will wait, but the thread will not.
When your method hits that await
(assuming it actually has some waiting to do), it will immediately return an incomplete task to the caller of SomeMethod
. The thread continues with whatever it wants to do. Later on, when the task being awaited completes, then SomeMethod
will resume executing. When SomeMethod
completes, the task it returned earlier will be completed.
I go into more detail on my blog post on the subject.
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