Compartilhar via


Erro do compilador CS4004

Não é possível aguardar em um contexto sem segurança

Exemplo

O exemplo a seguir gera o erro 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;
            }
        });
    }
}

Esse código gera um erro no C# 13 porque await está no bloco unsafe.

O método ReverseText usa com ingenuidade uma tarefa em segundo plano para criar de forma assíncrona uma nova cadeia de caracteres na ordem inversa de uma determinada cadeia de caracteres.

Para corrigir este erro

Separar o código não gerenciado do código aguardável corrigirá esse erro. Uma técnica de separação é criar um novo método para o código não seguro e, em seguida, chamá-lo a partir do código aguardável. Por exemplo:

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