Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async Task<bool> method call in if condition

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
}
like image 236
liferunsoncode Avatar asked Mar 08 '16 16:03

liferunsoncode


People also ask

What happens when you call async method?

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.

Is an async method that returns task?

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.

Can async return void?

Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.


1 Answers

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.

like image 95
Stephen Cleary Avatar answered Oct 26 '22 11:10

Stephen Cleary