Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 723
thegunner Avatar asked Mar 06 '26 13:03

thegunner


1 Answers

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.

like image 144
Jonas Benz Avatar answered Mar 09 '26 03:03

Jonas Benz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!