Partage via


Erreur du compilateur CS4004

Impossible d'attendre dans un contexte unsafe

Exemple

L’exemple suivant génère l’erreur 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;
            }
        });
    }
}

Ce code génère une erreur en C# 13, car le await se trouve dans le bloc unsafe.

La méthode ReverseText utilise naïvement une tâche en arrière-plan pour créer de façon asynchrone une chaîne dans l’ordre inverse d’une chaîne donnée.

Pour corriger cette erreur

Séparez le code non managé du code awaitable pour corriger cette erreur. Une technique de séparation consiste à créer une méthode pour le code unsafe, puis à l’appeler à partir du code awaitable. Par exemple :

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