Reputation: 61
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();
}
Upvotes: 1
Views: 83
Reputation: 171206
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).
Upvotes: 2