Is it possible for an I/O callback within a .NET W

2019-07-06 08:45发布

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条回答
够拽才男人
2楼-- · 2019-07-06 09:25

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

Task.Run(() => DoMyBiddingInTheBackground());
查看更多
登录 后发表回答