thegunner
thegunner

Reputation: 7153

Does awaiting for Task.Run always wait for response

I'm trying to implement an await Task.Run in my controller and then return the response.

Just curious if the response will always be got before we attempt to return it.

            var response = await Task.Run(() => _myService.GetResponse(refno));
            return Ok(response);

Could it attempt to return a response which hasn't been set yet?

Thanks

Upvotes: 3

Views: 1956

Answers (2)

Jonas Benz
Jonas Benz

Reputation: 503

Task.Run will immediately return an unfinished task. With the await you are waiting for the task to complete without blocking your thread. The task will only complete, when _myService.GetResponse(refno)) returns or throws a exception.

In short: Your response will always been set, when you hit your second line. But _myService.GetResponse(refno) could throw an exception. In this case the exception will be rethrown and you will not reach your second line.

Upvotes: 3

Stephen Cleary
Stephen Cleary

Reputation: 456342

var response = await Task.Run(() => _myService.GetResponse(refno));
return Ok(response);

Could it attempt to return a response which hasn't been set yet?

No; as you can see from the code, response is assigned to before it is returned. In fact, C# won't let you use unassigned variables; that's part of its type safety.

However, you should never do this! There's no benefit to doing await Task.Run on ASP.NET.

If you can change GetResponse to be asynchronous, then do that:

var response = await _myService.GetResponseAsync(refno);
return Ok(response);

Otherwise, just call it synchronously:

var response = _myService.GetResponse(refno);
return Ok(response);

Upvotes: 3

Related Questions