Reputation: 63728
If you are making an aysnc-enabled application, and you have to interact with a 3rd-party library which only provides blocking methods, what happens when an async
method blocks?
An easy example would be in .Net Framework, Socket.Receive
lets you set a timeout but then blocks. If a 3rd-party lib wraps this and I call it within an asyncronous methoddoes it simply mean whichever thread the runtime assigns to the Task
is blocked? Could it block other tasks or have other side-effects?
Upvotes: 0
Views: 1207
Reputation: 4461
If a 3rd-party lib wraps this and I call it within an asyncronous methoddoes it simply mean whichever thread the runtime assigns to the Task is blocked?
Yes. At best it blocks your task thread and at worst if you were in any Synchronization Context
(Desktop GUI
or ASP.NET Request Threads before .Net Core
) you'll be stuck in deadlock!
Could it block other tasks or have other side-effects?
If you wrap blocking method by thread named T which is defined like Task.Run(/* Blocking method */)
it will block T.
Upvotes: 1
Reputation: 5042
There is nothing wrong to block in an async
method. There are implications, though.
If you block in an async void
method, which is invoked by an UI event, you will also block the UI thread and make your UI unresponsive.
When you block in a async Task
method, or in any Task
you will of course block the thread that currently runs this part of the method or this task. If you run concurrently many instances of this task, or if your method gets executed concurrently (for example, it is a service method that gets called by many clients), you can exhaust the thread-pool. This can prevent other tasks from running, or other clients to call your service.
If you want to avoid the latter case, it might be worthy to run this blocking method in a long-running Task. The current implementation in .Net will create a separate thread for this task, thus not blocking a thread from the thread pool.
Upvotes: 1