Waiting for execution Task.Run always waits for a response

I am trying to execute Task.Run in my controller and then return a response.

Just wondering if the answer will always be received before we try to return it.

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

      

Could an attempt be made to return an answer that hasn't been set yet?

thank

+3


source to share


2 answers


Task.Run will immediately return the unfinished task. With waiting, you are waiting for the task to complete without blocking the thread. The task will complete when it _myService.GetResponse(refno))

returns or throws an exception.



In short: Your answer will always be set when you hit the second line. But it _myService.GetResponse(refno)

can throw an exception. In this case, the exception will be restored and you will not reach the second line.

+3


source


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

      

Could an attempt be made to return an answer that hasn't been set yet?

Not; as you can see from the code, response

is assigned before it is returned. In fact, C # won't let you use unassigned variables; this piece of security is of its own type.

However, you should never do this! It makes no sense to do it await Task.Run

in ASP.NET
.



If you can change GetResponse

to async, follow these steps:

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

      

Otherwise, just call it synchronously:

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

      

+3


source







All Articles