Is there any value in issuing "awaits" in Task started from the ThreadPool

It's pretty clear that using "await" to offload a Task from a UI thread is a great thing - the UI thread can then get back to handling Windows messages.

But let's say you start the awaited Task with Task.Run, which launches your code on a thread from the ThreadPool. Is there any value (any technically can it even be done?) to do an "await" in that code?

I'm tempted to say "no". Why would you want to offload work from a ThreadPool thread-- what else does it have to do except process the original task assigned to it?

Now, I would be REALLY impressed if someone replied and said that if I do an await, the ThreadPool thread can actually be "released" to the pool and used elsewhere, all while my async work continues...

Michael

Answers


technically can it even be done?

Yes. The resulting continuation will be run on a (likely) different ThreadPool thread, since there is no current SynchronizationContext. However, the mechanism works well.

Is there any value to do an "await" in that code?

Yes, there is. See below.

Why would you want to offload work from a ThreadPool thread-- what else does it have to do except process the original task assigned to it?

You could free up the thread to do other work. ThreadPool threads are a limited, finite resource.

Now, I would be REALLY impressed if someone replied and said that if I do an await, the ThreadPool thread can actually be "released" to the pool and used elsewhere, all while my async work continues..

Yes, this is effectively what happens.

Aside from the abililty to release the task, there is a another huge advantage to doing this - you can use the same method, with the same code, whether you're on the ThreadPool or a thread with a synchronization context. The ability to reuse the same code is hugely valuable, as well.


Need Your Help

Use a persistent notification to allow the user to return to running Android app

android notifications history android-notifications

I am developing an app with numerous Activities. I would like to create a persistent notification that (more or less) says, "AppName - Return to AppName" that will be present whenever my background