Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Awaitable methods in "if" condition – does execution wait for result of the method

Does this code make sense:

if (await CheckCondition1())
{
    Work1();
}
if (await CheckCondition2())
{
    Work2();
}
if (await CheckCondition3())
{
    Work3();
}

As awaited method is in if statement, does execution wait for result before going to next lines? Or will it rather result in calling "CheckCondition 1-3" methods in background and perform "Work" methods when results are ready?

In other words, if "CheckConditions" are long-running, will they be executed in parallel, or will they be executed sequentially as if it was synchronous code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

All three "check" methods are executed one after another (because of the await). If you want to execute them in parallel, you have to call these methods and await them after you called all of them:

Task<bool> task1 = CheckCondition1();
Task<bool> task2 = CheckCondition2();
Task<bool> task3 = CheckCondition3();
if(await task1)
{
   Work1();
}
if(await task2)
{
   Work2();
}
if(await task3)
{
   Work3();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading