davidfowl / AspNetCoreDiagnosticScenarios

This repository has examples of broken patterns in ASP.NET Core applications
7.69k stars 740 forks source link

Async methods inside a dedicated Thread #37

Closed forik closed 5 years ago

forik commented 5 years ago

Hi! Thanks for useful examples!

Let's say I've created a dedicated thread for some long running background work. Some part of the work involves connecting to some backend service using a ClientWebSocket, which has only async methods. That way I have no options but .Wait() for the results, do I?

davidfowl commented 5 years ago

That way I have no options but .Wait() for the results, do I?

That's right. You'll end up using multiple threads because websocket IO is always async. You'll be blocking the background thread and using another thread pool thread to unblock that thread. This is the sync over async issue.

davidfowl commented 5 years ago

There are some more advanced ways to reuse that background thread for continuations but it required writing a custom SynchronizationContext and/or TaskScheduler.

forik commented 5 years ago

There are some more advanced ways to reuse that background thread for continuations but it required writing a custom SynchronizationContext and/or TaskScheduler.

I also kept that in mind as an option. Thanks!