How to properly utilize Coarse Grain Concurrency With I/o Bound Work Using Tasks?

Viewed 43

Recently I have been just getting a bit confused on what to use for I/O Bound and Cpu Bound work and as of right now what I've concluded (feel free to correct) Is:

-Task.Run() - CPU bound work

-TaskCompletionSource - I/O bound work

Scenario:

You are stuck with a method that does i/o based work that runs sequentially and you cannot edit the method, What would be the best choice to make it run asynchronously?

//method example
//Purposely avoiding using the AsyncTask Version Of DownloadString In WebClient
public void Foo()=>new WebClient.DownloadString("https://google.com");

//-------

//here is the part of the code that I will be trying to execute Foo asynchronously
await Task.Run(()=>Foo()); //wouldn't this be the only way to run this method asynchronously even though Foo isn't doing CPU Bound Work?
1 Answers

What would be the best choice to make it run asynchronously?

In a 'normal' type of application, when you don't run the risk of thread-starvation: Task.Run(()=>Foo()); is indeed the only way to make it async.

In an ASP.NET application you should be much more concerened about how many threads you use. Making this async with Task.Run() is requesting an extra thread in order to block that thread. When you have other work that can run concurrently this helps to keep the response time down but it hurts the overall performance and scalability of your app.

So in a Controller Action, in general: don't do anything. Bite the bullet and block your current thread rather than requesting another thread just to await it.

Related