According to Microsoft Article here, It's better to use Threading for CPU-Bound tasks and Async\Await for IO-Bound. On the other hands, some post like here says: If you're talking about consuming asynchronous operations, async/await works excellently for both I/O-bound and CPU-bound. I know that Async\Await just uses the current context(single current Thread) and when an encounter with the time-consuming command, it returns control to man caller until the answer arrives.
With the above information, I have tried to test Sync\Await in a DotNet Windows application with the following code:
class SampleClass
{
public async Task<double> TestAsync()
{
HttpClient client = new HttpClient();
Task<double> doIt = DoWork();
double result = await doIt;
return result;
}
private async Task<double> DoWork()
{
//Line24: It takes a 4-sec CPU-Bound task and locks GUI when running
TimeConsumingCPUBound();
//Line27: It takes a 10-sec IO-Bound task and doesn't lock GUI when running
await Task.Delay(10000);
return 0;
}
public void TimeConsumingCPUBound()
{
string x = "";
for (int i = 0; i < 50000; i++)
{
x = x + i.ToString();
}
}
}
and here I call The code inside a bottom handler:
private async void button1_Click(object sender, EventArgs e)
{
SampleClass d = new SampleClass();
await d.TestAsync();
}
My question is Why is in line24(CPU-Bound) GUI is locked But in line27(IO-Bound) isn't it? I expected that in both of them GUI would be free!