Under what scenarios would one want to use
public async Task AsyncMethod(int num)
instead of
public async void AsyncMethod(int num)
The only scenario that I can think of is if you need the task to be able to track its progress.
Additionally, in the following method, are the async and await keywords unnecessary?
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
Foo()
would become FooAsync()
.
Thread.Sleep
with your tasks you should await Task.Delay(num)
instead
Task.Delay
is not Task.AsyncDelay
as all the methods on task are Async
async void
instead async Task
. The method crashed because it was using an Entity Framework context object declared as a member of the controller was disposed before the method finished to execute. The framework disposed the controller before its method finished to execute. I changed the method to async Task and it worked.
Normally, you would want to return a Task. The main exception should be when you need to have a void return type (for events). If there's no reason to disallow having the caller await your task, why disallow it? async methods that return void are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception. The easiest way is to show the difference is with an example:
static async void f()
{
await h();
}
static async Task g()
{
await h();
}
static async Task h()
{
throw new NotImplementedException();
}
private void button1_Click(object sender, EventArgs e)
{
f();
}
private void button2_Click(object sender, EventArgs e)
{
g();
}
private void button3_Click(object sender, EventArgs e)
{
GC.Collect();
}
f
's exception is always "observed". An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. g
's exception is never observed. When the garbage collector comes to clean up the task, it sees that the task resulted in an exception, and nobody handled the exception. When that happens, the TaskScheduler.UnobservedTaskException
handler runs. You should never let this happen. To use your example,
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
Yes, use async
and await
here, they make sure your method still works correctly if an exception is thrown.
For more information see: https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
I have come across this very useful article about async
and void
written by Jérôme Laban: https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html
The bottom line is that an async+void
can crash the system and usually should be used only on the UI side event handlers.
The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event. When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.
The problem with calling async void is that
you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing
Here are the three ways to call an async function:
async Task
I think you can use async void
for kicking off background operations as well, so long as you're careful to catch exceptions. Thoughts?
class Program {
static bool isFinished = false;
static void Main(string[] args) {
// Kick off the background operation and don't care about when it completes
BackgroundWork();
Console.WriteLine("Press enter when you're ready to stop the background operation.");
Console.ReadLine();
isFinished = true;
}
// Using async void to kickoff a background operation that nobody wants to be notified about when it completes.
static async void BackgroundWork() {
// It's important to catch exceptions so we don't crash the appliation.
try {
// This operation will end after ten interations or when the app closes. Whichever happens first.
for (var count = 1; count <= 10 && !isFinished; count++) {
await Task.Delay(1000);
Console.WriteLine($"{count} seconds of work elapsed.");
}
Console.WriteLine("Background operation came to an end.");
} catch (Exception x) {
Console.WriteLine("Caught exception:");
Console.WriteLine(x.ToString());
}
}
}
According to Microsoft documentation, should NEVER use async void
Do not do this: The following example uses async void which makes the HTTP request complete when the first await is reached: Which is ALWAYS a bad practice in ASP.NET Core apps. Accesses the HttpResponse after the HTTP request is complete. Crashes the process.
async void
but about using the http context after request completion. They cause this by using a bad async action returning void, forbidding the pipeline to await after it. So that is no general recommendation about async void
, but just an example case of bad consequences it can have.
My answer is simple you can not await void method
Error CS4008 Cannot await 'void' TestAsync e:\test\TestAsync\TestAsyncProgram.cs
So if the method is async
, it is better to be awaitable, because you can lose the advantage ofasync
.
Success story sharing
f
instead ofg
in my comment. The exception fromf
is passed to theSynchronizationContext
.g
will raiseUnobservedTaskException
, butUTE
no longer crashes the process if it's not handled. There are some situations where it's acceptable to have "asynchronous exceptions" like this that are ignored.WhenAny
with multipleTask
s resulting in exceptions. You often only have to handle the first one, and you often want to ignore the others.WhenAny
in the first place whether it's okay to ignore the other exceptions: the main use case I have for it still ends up awaiting the remaining tasks when any finishes, with or without an exception.