3

Trying to write an API, and I have a weird case which I tried to solve like:

        if (!request.WillCheckGetLater)
        {
            // Client calling is willing to wait only for certain amount of time
            var clientWillingToWaitFor = GetResponseTime(request);
            var needsToUpdateResponse = await AwaitResponse(heldBidRequest, clientWillingToWaitFor);
            SendMessage(...);
            return needsToUpdateResponse;
        }
        else
        {
            SendMessage(...);
            return false;
        }

While on my Post method I'm trying to await that method. Basically when I get a post, I construct a "short" answer, and the client check the "long" answer with the GET method from the API, but can also ask directly for the long answer in the POST, but has to specify how much he's willing to wait for that long answer, otherwise I default to a "short" answer...

My SendMessage method is basically third party communication system where I subscribe and publish messages.

right now, when the line

 var needsToUpdateResponse = await AwaitResponse(heldBidRequest, clientWillingToWaitFor);

executes, it blocks this piece of code and SendMessage doesn't execute until the task over, ideally I would rather have it blocked on the return instead.

I don't necessary want to call SendMessage First just because of the weird scenario I could get that the response from the message comes before I set up for waiting for it.

Any ideas of what I could use to do that?

CPay
  • 47
  • 6

2 Answers2

5

Yes

In fact, you are already waiting on the "variable" (really the return value). You cannot await a method, only a task. Just store off the task instead of T and await it when you are ready:

var needsToUpdateResponse = AwaitResponse(heldBidRequest, clientWillingToWaitFor);
SendMessage(...);
return await needsToUpdateResponse;

It would be more obvious if we didn't use var:

Task<T> needsToUpdateResponse = AwaitResponse(heldBidRequest, clientWillingToWaitFor);
SendMessage(...);
return await needsToUpdateResponse;
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
0

You can get the awaiter from the task, and get the result where you want. But basically you await on the method when you need the result.

Please see this reference https://stackoverflow.com/a/17284612/819153

Community
  • 1
  • 1
Zinov
  • 3,817
  • 5
  • 36
  • 70