简体   繁体   English

由OwinCommunicationListener托管的Async Web Api中的Fire and Forget方法

[英]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. 我们在由OwinCommunicationListener托管的服务矩阵群集中托管了一个Web API。

[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. 据我了解,这应该是DoSomethingAsync方法完成与处理请求之间的竞争条件,并且应该抛出TaskCancelledException或以后提早完成的某些操作,但是永远不会成功。

I am expecting some error since the task DoSomething is not awaited and yet it completes its work everytime. 我期待出现一些错误,因为任务DoSomething尚未等待,但每次都能完成其工作。 If I add 如果我加

await Task.Delay(10000);

then the API response almost instantaneously and after the 10 seconds rest of the code is executed. 然后,API几乎立即就会响应,并在10秒钟后执行其余代码。 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. 没有什么可以将请求对象与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. 但是,即使您将RequestObj引用权限直接传递给DoSomethingAsync,该方法也不会出现问题,因为在引用对象时GC不会收集您的RequestObj。 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. 同样,一旦异步执行开始,它就拥有了自己的生命,这意味着回调可能在另一个线程上完成,但已与请求处理管道一起调度了该线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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