I'm still having trouble wrapping my head around async/await. I'm trying to figure out if I need to wrap my CPU intensive workload in a Task.Run below. Can someone tell me which is the better way to do this?
Without Task.Run:
public async Task ProcessData()
{
//Get some data
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("myUrl");
string data = await response.Content.ReadAsStringAsync();
//Calculate result
string result = null;
for (int i = 0; i < 10000000; i++)
{
//Do some CPU intensive work
}
//Save results
using (var fs = new FileStream("myFile.txt", FileMode.Create))
using (var writer = new StreamWriter(fs))
{
await writer.WriteLineAsync(result);
}
}
With Task.Run:
public async Task ProcessData()
{
//Get some data
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("myUrl");
string data = await response.Content.ReadAsStringAsync();
//Calculate result
string result = null;
await Task.Run(() =>
{
for (int i = 0; i < 10000000; i++)
{
//Do some CPU intensive work
}
});
//Save results
using (var fs = new FileStream("myFile.txt", FileMode.Create))
using (var writer = new StreamWriter(fs))
{
await writer.WriteLineAsync(result);
}
}
My instinct is to not use the Task.Run but in that case would that mean that all code in an async method is going to be executed on a separate thread? Meaning the calling thread will not be interrupted until the very end (File stream is closed and method ends)?
Or will the caller thread be interrupted and go back to this method to do the CPU intensive part first and then go back to whatever it was doing while ProcessData() runs in the background for the FileStream part?
I hope that's clear.
Thanks in Advance