C# Error CS4004 – Cannot await in an unsafe context

C# Error

CS4004 – Cannot await in an unsafe context

Reason for the Error & Solution

Cannot await in an unsafe context

Example

The following sample generates CS4004:

using System.Threading.Tasks;

public static class C
{
    public static unsafe async Task<string> ReverseTextAsync(string text)
    {
        return await Task.Run(() =>
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            fixed (char* pText = text)
            {
                char* pStart = pText;
                char* pEnd = pText + text.Length - 1;
                for (int i = text.Length / 2; i >= 0; i--)
                {
                    char temp = *pStart;
                    *pStart++ = *pEnd;
                    *pEnd – = temp;
                }

                return text;
            }
        });
    }
}

The ReverseText method naively uses a background task to asynchronously create a new string in reverse order of a given string.

To correct this error

Separating the unsafe code from the awaitable code will correct this error. One separation technique is creating a new method for the unsafe code and then calling it from the awaitable code. For example:

public static class C
{
    public static async Task<string> ReverseTextAsync(string text)
    {
        return await Task.Run(() => ReverseTextUnsafe(text));
    }

    private static unsafe string ReverseTextUnsafe(string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return text;
        }

        fixed (char* pText = text)
        {
            char* pStart = pText;
            char* pEnd = pText + text.Length - 1;
            for (int i = text.Length / 2; i >= 0; i--)
            {
                char temp = *pStart;
                *pStart++ = *pEnd;
                *pEnd – = temp;
            }

            return text;
        }
    }
}