I have some IO-Bound jobs(periodically write some data to file) codes as follows:
public async Task SaveToFile1(int sleepTimeout)
{
while (true)
{
// Do file saving work
await Task.Delay(sleepTimeout).ConfigureAwait(false);
}
}
public async Task SaveToFile2(int sleepTimeout)
{
while (true)
{
// Do file saving work
await Task.Delay(sleepTimeout).ConfigureAwait(false);
}
}
public async Task SaveToFile3(int sleepTimeout)
{
while (true)
{
// Do file saving work
await Task.Delay(sleepTimeout).ConfigureAwait(false);
}
}
The caller is the main method. The tasks worked fine and produced the correct result when I run them with 2 ways as follows:
void main ()
{
// other codes
// way 1:
SaveToFile1(1000);
SaveToFile2(1000);
SaveToFile3(1000);
// other codes will not let the app exit
}
void main ()
{
// other codes
// way 2:
Task.Run(async() => await SaveToFile1(1000));
Task.Run(async() => await SaveToFile2(1000));
Task.Run(async() => await SaveToFile3(1000));
// other codes will not let the app exit
}
Which is the right way or another way is the best choice for my situation?
Thanks for your answers!
Edit:
In way 1, when await Task.Delay
'complete', a new thread-pool thread may be captured to execute the loop's next step, ..., loop will always running in other thread at the await
hit.
In way 2, may be a new thread-pool thread will be used when Task.Run
execute immediately, loop will always running in other thread at the begin.
The result are the same, where is the diffrence?
So my question is not about Task.Run vs async-await!