Use async/await or Task.Run in a continuous work?

Viewed 404

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.

1 Answers

So, is it necessary to change Task.Run to async/await form?

No, if you don't care about any return value from the task, you don't have to to await it. You could just set IsWorking to false to let the thread finish eventually.

If you want to be able to determine when it has finished, you should keep a reference to the Task and await it.

If you want to run something on a background thread "forever" or for a very long time, you should either create a Thread or use the overload of Task.Factory.StartNew that accepts a TaskCreationOptions.LongRunning:

Task.Factory.StartNew(() => { ... }, 
    TaskCreationOptions.LongRunning);

This gives the TPL a hint to run your action on a dedicated thread rather than "stealing" one from the thread pool.

Related