0

From my desktop UI I need to make a call to a web service (a long running operation). Let's say the API returns a Boolean value. Now it could take several seconds to receive a response. When I invoke this API I would like the UI to still be responsive.

I've wrapped the call to the API with a Task.Run(). From within this Task.Run action I return the value like this:

Task.FromResult<bool>(result);

The method which contains this Task.Run() has a signature like this:

public async Task<bool> GetStatus();

Now when I run all this, it appears to be working. But I am not convinced this is working the way I think it's working.

Can anybody tell me if my explanation here is correct?

  1. The Task.Run() allows its contents to run asynchronously.
  2. The method which contains Task.Run() will return immediately.
  3. When the async Task is completed, any code that exists below the Task.Run() line will be executed.
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
AlvinfromDiaspar
  • 6,611
  • 13
  • 75
  • 140
  • Your #3 point is only correct if you also use `await`. See marked duplicate, as well as the extensive documentation on `Task.Run()` and `await` that exists, along with the hundreds of similar questions already on Stack Overflow. – Peter Duniho Jan 24 '20 at 21:42
  • 1
    Task.Run() will return immediately and the control will go to the next command. The function or delegate that you queued will be run asynchronously. – PraveenB Jan 24 '20 at 21:43
  • `public async void Main() { DoStuffBefore(); var result = await GetStatus(); DoStuffAfterwards(); }` `public async Task GetStatus() { return await Task.Run(() => MyApiCall()); }` `private bool MyApiCall(){ Thread.Sleep(1000); return true; }` – Welcor Jan 24 '20 at 22:17

0 Answers0