[c#] async/await - when to return a Task vs void?

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));
}

This question is related to c# asynchronous .net-4.5

The answer is


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.


I got clear idea from this statements.

  1. Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext(SynchronizationContext represents a location "where" code might be executed. ) that was active when the async void method started

Exceptions from an Async Void Method Can’t Be Caught with Catch

private async void ThrowExceptionAsync()
{
  throw new InvalidOperationException();
}
public void AsyncVoidExceptions_CannotBeCaughtByCatch()
{
  try
  {
    ThrowExceptionAsync();
  }
  catch (Exception)
  {
    // The exception is never caught here!
    throw;
  }
}

These exceptions can be observed using AppDomain.UnhandledException or a similar catch-all event for GUI/ASP.NET applications, but using those events for regular exception handling is a recipe for unmaintainability(it crashes the application).

  1. Async void methods have different composing semantics. Async methods returning Task or Task can be easily composed using await, Task.WhenAny, Task.WhenAll and so on. Async methods returning void don’t provide an easy way to notify the calling code that they’ve completed. It’s easy to start several async void methods, but it’s not easy to determine when they’ve finished. Async void methods will notify their SynchronizationContext when they start and finish, but a custom SynchronizationContext is a complex solution for regular application code.

  2. Async Void method useful when using synchronous event handler because they raise their exceptions directly on the SynchronizationContext, which is similar to how synchronous event handlers behave

For more details check this link https://msdn.microsoft.com/en-us/magazine/jj991977.aspx


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<T> SomethingAsync() { ... return t; }
async Task SomethingAsync() { ... }
async void SomethingAsync() { ... }

In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.

In the first case, the function returns a task that eventually produces the t.

In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.

The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.

The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.


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());
        }
    }
}

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 loose async advantage.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asynchronous

How to read file with async/await properly? Use Async/Await with Axios in React.js Waiting until the task finishes How to reject in async/await syntax? React - Display loading screen while DOM is rendering? angular 2 how to return data from subscribe How do I access store state in React Redux? SyntaxError: Unexpected token function - Async Await Nodejs Why does .json() return a promise? Why is setState in reactjs Async instead of Sync?

Examples related to .net-4.5

There is no argument given that corresponds to the required formal parameter - .NET Error The type or namespace name 'System' could not be found Which versions of SSL/TLS does System.Net.WebRequest support? async at console app in C#? Is it possible to run a .NET 4.5 app on XP? Awaiting multiple Tasks with different results Do you have to put Task.Run in a method to make it async? C# HttpClient 4.5 multipart/form-data upload Do HttpClient and HttpClientHandler have to be disposed between requests? What is the correct way to read a serial port using .NET framework?