2

I am new to c# and trying to understand the difference between following two implementations. Looks like they both are doing exactly same and the output is exactly same. If both cases are invoking the run method synchronously, what value does async await really providing? Or there is really no benefit here?

private async Task<int> MyTask(CancellationToken cancellationToken)
{
    Log.Debug("Task started");
    await Task.Delay(5000, cancellationToken);
    Log.Debug("Task ended");
    return 0;
}
public async Task<int> Run()
{
    var result = await MyTask(_cancellationToken);
    return result;
}

This how Run method is called

var returnCode = jobRunner.Run().Result;

And this implementation?

private int MyTask(CancellationToken cancellationToken)
{
    Log.Debug("Task started");
    var task = Task.Delay(5000, cancellationToken);
    task.Wait(cancellationToken);
    Log.Debug("Task ended");
    return 0;
}

public int Run()
{
    var result = MyTask(_cancellationToken);
    return result;
}

This how Run method is called in this case

var returnCode = jobRunner.Run();
jbl
  • 123
  • 7
  • Related question: [If async-await doesn't create any additional threads, then how does it make applications responsive?](https://stackoverflow.com/questions/37419572/if-async-await-doesnt-create-any-additional-threads-then-how-does-it-make-appl) – ProgrammingLlama Oct 04 '17 at 01:23
  • 1
    In your use case there is no difference because at the end you are invoking them synchronously. This not a real use case for async await pattern. If you implement your entire call stack to follow async await pattern then you will see the real benefit. – Vinod Oct 04 '17 at 02:03
  • 2
    Your question is: scenario one: I made a to-do list that said "wait ten minutes then write down that I finished". Then I started doing everything on my to-do list; I waited ten minutes, and then I wrote down that I finished. Scenario two: I waited ten minutes, then I wrote down that I was finished. **What is the difference between these scenarios?** There is no difference.The scenario you *should* be considering is *I made a to-do list that said to wait ten minutes then write down that I'm finished, I started doing my to-do list, and **while I was waiting I made a sandwich**. – Eric Lippert Oct 04 '17 at 02:10
  • 1
    That's the power of asynchrony: that you can do other things *while you are waiting*. Write a program that does something else while you're waiting! – Eric Lippert Oct 04 '17 at 02:11
  • @EricLippert You provided really good explanation. Thank you. – jbl Oct 04 '17 at 02:17

0 Answers0