Thursday, January 31, 2013

Easy way to avoid warning CS4014

You will get a warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed if you call async method from another async method without await.

For example, the following code will generate a warning:

namespace Vurdalakov
{
    using System;
    using System.Threading.Tasks;

    public class WarningCS4014
    {
        public async void Run()
        {
            Log("Lorem ipsum dolor sit amet"); // Warning CS4014
        }

        public async Task Log(String text)
        {
            // write exception to log asynchronously
        }
    }
}

Solution 1 (my favorite): assign the result of the async method to a local variable:

var task = Log("Lorem ipsum dolor sit amet");

Solution 2: use #pragma warning preprocessor directive:

#pragma warning disable 4014
Log("Lorem ipsum dolor sit amet");
#pragma warning restore 4014

1 comment:

  1. The first solution is not practical as the compiler will warn the variable task is not used...

    ReplyDelete