Is it possible for an I/O callback within a .NET Windows Service that calls C#'s await to not block?

别来无恙 提交于 2019-12-23 21:25:04

问题


I know that in ASP.NET that the worker thread goes back to the pool when await is used while the I/O happens in the background, which is great for scalability.

My Windows Service is a socket server, and it uses Begin / End style async socket I/O. Mixing my magic, I know. I'm in the EndRead callback, receiving a request to do work. I don't want the thread that made the callback to block.

I'm using the Nito.AsyncEx library, using AsyncContext.Run(() => DoMyBiddingHopefullyInTheBackground(...))...

private void EndRead(IAsyncResult result)
{
    int nRead = m_socketStream.EndRead(result);
    ...
    AsyncContext.Run(() => DoMyBiddingHopefullyInTheBackground(...))
}

private async Task DoMyBiddingHopefullyInTheBackground(...)
{
    await DoSomeAsyncIoWork();
}

Using AsyncContext was the only way I could find for non-async-marked code to call async-marked code that uses await.

Will AsyncContext.Run block the thread that called my socket End callback routine? If so, is there any way to make it so that that thread goes back to the thread pool during the async / await I/O?


回答1:


If you want to run an async method and you don't want to wait for it to complete, try this:

Task.Run(() => DoMyBiddingInTheBackground());


来源:https://stackoverflow.com/questions/21338300/is-it-possible-for-an-i-o-callback-within-a-net-windows-service-that-calls-cs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!