warning this call is not awaited, execution of the current method continues

C#Async Await

C# Problem Overview


Just got VS2012 and trying to get a handle on async.

Let's say I've got an method that fetches some value from a blocking source. I don't want caller of the method to block. I could write the method to take a callback which is invoked when the value arrives, but since I'm using C# 5, I decide to make the method async so callers don't have to deal with callbacks:

// contrived example (edited in response to Servy's comment)
public static Task<string> PromptForStringAsync(string prompt)
{
	return Task.Factory.StartNew(() => {
		Console.Write(prompt);
		return Console.ReadLine();
	});
}

Here's an example method that calls it. If PromptForStringAsync wasn't async, this method would require nesting a callback within a callback. With async, I get to write my method in this very natural way:

public static async Task GetNameAsync()
{
	string firstname = await PromptForStringAsync("Enter your first name: ");
	Console.WriteLine("Welcome {0}.", firstname);

	string lastname = await PromptForStringAsync("Enter your last name: ");
	Console.WriteLine("Name saved as '{0} {1}'.", firstname, lastname);
}

So far so good. The problem is when I call GetNameAsync:

public static void DoStuff()
{
	GetNameAsync();
	MainWorkOfApplicationIDontWantBlocked();
}

The whole point of GetNameAsync is that it's asynchronous. I don't want it to block, because I want to get back to the MainWorkOfApplicationIDontWantBlocked ASAP and let GetNameAsync do its thing in the background. However, calling it this way gives me a compiler warning on the GetNameAsync line:

Warning	1	Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

I'm perfectly aware that "execution of the current method continues before the call is completed". That's the point of asynchronous code, right?

I prefer my code to compile without warnings, but there's nothing to "fix" here because the code is doing exactly what I intend it to do. I can get rid of the warning by storing the return value of GetNameAsync:

public static void DoStuff()
{
	var result = GetNameAsync(); // supress warning
	MainWorkOfApplicationIDontWantBlocked();
}

But now I have superfluous code. Visual Studio seems to understand that I was forced to write this unnecessary code, because it suppresses the normal "value never used" warning.

I can also get rid of the warning by wrapping GetNameAsync in a method that's not async:

	public static Task GetNameWrapper()
	{
		return GetNameAsync();
	}

But that's even more superfluous code. So I have to write code I don't need or tolerate an unnecessary warning.

Is there something about my use of async that's wrong here?

C# Solutions


Solution 1 - C#

If you really don't need the result, you can simply change the GetNameAsync's signature to return void:

public static async void GetNameAsync()
{
    ...
}

Consider to see answer to a related question: What's the difference between returning void and returning a Task?

Update

If you need the result, you can change the GetNameAsync to return, say, Task<string>:

public static async Task<string> GetNameAsync()
{
    string firstname = await PromptForStringAsync("Enter your first name: ");
    string lastname = await PromptForStringAsync("Enter your last name: ");
    return firstname + lastname;
}

And use it as follows:

public static void DoStuff()
{
    Task<string> task = GetNameAsync();

    // Set up a continuation BEFORE MainWorkOfApplicationIDontWantBlocked
    Task anotherTask = task.ContinueWith(r => {
            Console.WriteLine(r.Result);
        });

    MainWorkOfApplicationIDontWantBlocked();

    // OR wait for the result AFTER
    string result = task.Result;
}

Solution 2 - C#

I'm quite late to this discussion, but there is also the option to use the #pragma pre-processor directive. I have some async code here and there that I explicitly do not want to await in some conditions, and I dislike warnings and unused variables just like the rest of you:

#pragma warning disable 4014
SomeMethodAsync();
#pragma warning restore 4014

The "4014" comes from this MSDN page: Compiler Warning (level 1) CS4014.

See also the warning/answer by @ryan-horath here https://stackoverflow.com/a/12145047/928483.

> Exceptions thrown during an async call that is not awaited will be lost. To get rid of this warning, you should assign the Task return value of the async call to a variable. This ensures you have access to any exceptions thrown, which will be indicated in the return value.

Update for C# 7.0

C# 7.0 adds a new feature, discard variables: Discards - C# Guide, which can also help in this regard.

_ = SomeMethodAsync();

Solution 3 - C#

I'm not particularly fond of the solutions that either assign the task to an unused variable, or changing the method signature to return void. The former creates superfluous, non-intuitive code, while the latter may not be possible if you're implementing an interface or have another usage of the function where you want to use the returned Task.

My solution is to create an extension method of Task, called DoNotAwait() that does nothing. This will not only suppress all warnings, ReSharper or otherwise, but makes the code more understandable, and indicates to future maintainers of your code that you really intended for the call to not be awaited.

Extension method:

public static class TaskExtensions
{
    public static void DoNotAwait(this Task task) { }
}

Usage:

public static void DoStuff()
{
    GetNameAsync().DoNotAwait();
    MainWorkOfApplicationIDontWantBlocked();
}

Edited to add: this is similar to Jonathan Allen's solution where the extension method would start the task if not already started, but I prefer to have single-purpose functions so that the caller's intent is completely clear.

Solution 4 - C#

async void IS BAD!

  1. https://stackoverflow.com/questions/8043296/whats-the-difference-between-returning-void-and-returning-a-task/8043882#8043882
  2. https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

What I suggest is that you explicitly run the Task via an anonymous method...

e.g.

public static void DoStuff()
{
    Task.Run(async () => GetNameAsync());
    MainWorkOfApplicationIDontWantBlocked();
}

Or if you did want it to block you can await on the anonymous method

public static void DoStuff()
{
    Task.Run(async () => await GetNameAsync());
    MainWorkOfApplicationThatWillBeBlocked();
}

However, if your GetNameAsync method has to interact with UI or even anything UI bound, (WINRT/MVVM, I'm looking at you), then it gets a little funkier =)

You'll need to pass the reference to the UI dispatcher like this...

Task.Run(async () => await GetNameAsync(CoreApplication.MainView.CoreWindow.Dispatcher));

And then in your async method you'll need to interact with your UI or UI bound elements thought that dispatcher...

dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {  this.UserName = userName; });

Solution 5 - C#

This is what I'm currently doing:

SomeAyncFunction().RunConcurrently();

Where RunConcurrently is defined as...

 /// <summary> 
 /// Runs the Task in a concurrent thread without waiting for it to complete. This will start the task if it is not already running. 
 /// </summary> 
 /// <param name="task">The task to run.</param> 
 /// <remarks>This is usually used to avoid warning messages about not waiting for the task to complete.</remarks> 
 public static void RunConcurrently(this Task task) 
 { 
     if (task == null) 
         throw new ArgumentNullException("task", "task is null."); 

     if (task.Status == TaskStatus.Created) 
         task.Start(); 
 } 

https://github.com/docevaad/Anchor/blob/master/Tortuga.Anchor/Tortuga.Anchor.source/shared/TaskUtilities.cs

https://www.nuget.org/packages/Tortuga.Anchor/

Solution 6 - C#

According to the Microsoft article on this warning, you can solve it by simply assigning the returned task to a variable. Below is a translation of the code provided in the Microsoft example:

    // To suppress the warning without awaiting, you can assign the 
    // returned task to a variable. The assignment doesn't change how
    // the program runs. However, the recommended practice is always to
    // await a call to an async method.
    // Replace Call #1 with the following line.
    Task delayTask = CalledMethodAsync(delay);

Note that doing this will result in the "Local variable is never used" message in ReSharper.

Solution 7 - C#

Here, a simple solution.

public static class TasksExtensions
{
    public static void RunAndForget(this Task task)
    {
    }
}

Regards

Solution 8 - C#

It's your simplified example that causes the superflous code. Normally you would want to use the data that was fetched from the blocking source at some point in the program, so you would want the result back so that it would be possible to get to the data.

If you really have something that happens totally isolated from the rest of the program, async would not be the right approach. Just start a new thread for that task.

Solution 9 - C#

If you don't want to change the method signature to return void (as returning void should always be avoided), you can use C# 7.0+ Discard feature like this, which is slightly better than assigning to a variable (and should remove most other source validation tools warnings):

public static void DoStuff()
{
    _ = GetNameAsync(); // we don't need the return value (suppresses warning)
    MainWorkOfApplicationIDontWantBlocked();
}

Solution 10 - C#

Do you really want to ignore the result? as in including ignoring any unexpected exceptions?

If not you might want a look at this question: Fire and Forget approach,

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMudView Question on Stackoverflow
Solution 1 - C#Nikolay KhilView Answer on Stackoverflow
Solution 2 - C#WillemView Answer on Stackoverflow
Solution 3 - C#Joe SavageView Answer on Stackoverflow
Solution 4 - C#MrEsView Answer on Stackoverflow
Solution 5 - C#Jonathan AllenView Answer on Stackoverflow
Solution 6 - C#devlordView Answer on Stackoverflow
Solution 7 - C#JuanluElGuerreView Answer on Stackoverflow
Solution 8 - C#GuffaView Answer on Stackoverflow
Solution 9 - C#Simon MourierView Answer on Stackoverflow
Solution 10 - C#JensView Answer on Stackoverflow