简体   繁体   中英

Fire and Forget method in Async Web Api hosted in OwinCommunicationListener

Recently I can across a code that we are using and is working fine and for the life of me I cannot figure out why.

We have a web API hosted in a service fabric cluster that is hosted over OwinCommunicationListener.

[HttpPost]
public async Task<HttpResponseMessage> WebApiMethod(RequestObject request)
{
   string test;
   SomeObject obj;
   ....
   DoSomethingAsync(test, obj);
   return this.ActionContext.CreateResponse(HttpStatusCode.OK, new { Status = "Success" });
}


private async Task DoSomethingAsync(string param1, SomeObject param2)
{
    .....
    await SomeOtherAsyncMethod();
    .....
}

As far as I understand it should be a race condition between the method completion of DoSomethingAsync and the request disposing off and should throw an TaskCancelledException or something if later completes early, but it never does.

I am expecting some error since the task DoSomething is not awaited and yet it completes its work everytime. If I add

await Task.Delay(10000);

then the API response almost instantaneously and after the 10 seconds rest of the code is executed. Shouldn't by that time the host thread should be disposed since the original call was a Fire-and-Forget (not awaited).

What am I missing here.

There is nothing that ties request object with DoSomethingAsync. But even if you pass RequestObj reference right into DoSomethingAsync, the method will get completed with no problem as GC won't collect your RequestObj while you're referencing the object. Also, once async execution kicks off, it lives its own life meaning the callback might be completed on a different thread but the one that request-handling pipeline has been dispatched with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM