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

When is it asynchronous and when is synchronous

Having read a /lot/ of documentation on the async await pattern I thought I had a pretty good handle on the pattern. I read all about async all the way then read another article that mentions ‘if it runs in under 50 milliseconds don’t async it’. It seems there is conflicting information and/or opinions and I have managed to just confuse myself. I have also read that Task.Yield() will force an async decorated method to run asynchronously.

Given the following code:

    static async Task MethodA() {
        await MethodB().ConfigureAwait(false);
    }

    static async Task MethodB() {
        await Task.Yield();
        MethodC();
    }

    static void MethodC() {
        // do some synchronous stuff
    }

    static async Task Main(string[] args) {
        var task1 = Task.Run(() => MethodA().ConfigureAwait(false));
        var task2 = Task.Run(() => MethodB().ConfigureAwait(false));

        await Task.WhenAll(new List<Task>() { task1, task2 });
    }

Will MethodC run synchronously or asynchronously, I assumed asynchronously as it was called from an asynchronous method. Also, is Task.Yield necessary at all?

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

To be honest this is doing my head in, every article I have read delves deeper and deeper into the async await pattern with the whys and wherefores and is just adding more complexity to the question. Just looking for a simple answer.

>Solution :

Will MethodC run synchronously or asynchronously

Synchronously. It has a synchronous signature, so it will always run synchronously.

I assumed asynchronously as it was called from an asynchronous method

The context from which it is called is irrelevant to how MethodC will run.

is Task.Yield necessary at all

Well it will force MethodB to yield a Task before MethodC runs, but this will be incomplete until MethodC finishes, and because MethodC is synchronous (does not release the thread) it achieves nothing useful.

Just looking for a simple answer

async bubbles up the call stack, and because you are not consuming an async method here (MethodC is synchronous) you should not be using async at all.

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