0

Let's say I have a function return Task<bool>, basically I can implement it in 2 ways, what is the difference, pros/cons?

public async Task<bool> FooAsync()
{
    return await Task.Run(() => 
    {
        Thread.Sleep(100);
        return true;
    });
}

public Task<bool> FooAsync()
{
    return Task.Run(() => 
    {
        Thread.Sleep(100);
        return true;
    });
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
codewarrior
  • 723
  • 7
  • 22

2 Answers2

0

The difference is of asynchrony (code can move further after calling this, response will come) vs parallelism (parallel code execution)

Amit Kumar Singh
  • 4,393
  • 2
  • 9
  • 22
0

Well, it's actually not necessary to return a Task<bool> in your first example since you already awaited it and got the result.

The difference between the two examples is that in your first case you actually await the given Task which will unwrap the result, which means you already have the boolean to work with.

The second example will actually return a Task<bool> which represents the ongoing work of returning a boolean and it basically says it will return a boolean in the future. Whoever uses your method is responsible to await in order to get the result wanted.

Kerim Emurla
  • 1,141
  • 8
  • 15