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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...