1

Is it appropriate to use async void method to start some long-living operation? I know Nito or Task.Run() could be used to Run Task from non-async method. What is the difference? Are there any pitfalls?

By all that I mean, can I write like that:

async void bar()
{
    try
    {
        //...
    }
    catch (Exception ex)
    {
        // no rethrowing here
    }
}

void foo()
{
    bar();
    // will continue right after 1st await in bar()
    baz();
}
Community
  • 1
  • 1
ilivit
  • 41
  • 1
  • 7
  • Why not do `async Task` and just not await bar? – Scott Chamberlain Jan 14 '16 at 14:06
  • @ScottChamberlain But will it start asynchronously if not awaited later in code? – ilivit Jan 14 '16 at 14:08
  • Doing async void and doing async Task without awaiting the returned task has the exact same behavior. calling await does not start a task, it waits for a already started task to finish. That is why if you call await on a task that was started with `new Task()` and never had `.Start()` called on it the await will wait forever because the task is not running. – Scott Chamberlain Jan 14 '16 at 14:12

1 Answers1

2

In any case it would be better to use async Task to get better error handling behavior. You don't need to await the resulting task.

In your code snippet the comment will continue right after 1st await in bar is not necessarily correct. As it stands bar will synchronously execute and block foo because bar has no awaits in it.

Starting a long running operation requires to either use async IO or to use a new thread/task in some way (Task.Run is appropriate).

usr
  • 168,620
  • 35
  • 240
  • 369
  • +1 I recall Stephen Toub's comment on async/await: "no keyword in c# starts a thread - there should be some API call (Task.Run(), File.ReadAsync()....)" – alexm Jan 14 '16 at 16:54