I am confused about whether to use async/await or Task.Run when encountering continuous long running work. I've read a lot material and examples about asynchronous programming, but most of them are concerned with work whose ending could be predicted. In my application, which is a WPF app with MVVM, main work of the app is doing endless loop in which the time-consuming work lays. The main logic of the work looks like this:
// this method is fired by a command which binds to a button
private void OnStart()
{
Task.Run(() =>
{
var sw = new StopWatch();
sw.Start();
while(IsWorking)
{
TimeConsumingWork();
sw.Stop();
if (sw.ElapsedMiiliseconds >= 1000)
{
Thread.Sleep(1000 - sw.ElapsedMilliseconds);
sw.Restart();
}
}
});
}
I start/stop the time-consuming work by a toggle button, and the time-consuming work will loop forever for a long time(expect 4-30 days). The time-consuming work contains a considerable IO-bound, which is appending a (6-13cols ⨉ 1000-20000rows) data to a csv file per seconds.
So, is it necessary to change Task.Run to async/await form? It seems like it would be more preferable to use async/await rather than Task.Run.