Condividi tramite


Errore del compilatore CS4004

Non è possibile attendere in un contesto non sicuro

Esempio

L'esempio seguente genera l'errore 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;
            }
        });
    }
}

Questo codice genera un errore in C# 13 perché await si trova nel blocco unsafe.

Il metodo ReverseText usa in modo nativo un'attività in background per creare in modo asincrono una nuova stringa in ordine inverso di una determinata stringa.

Per correggere l'errore

La separazione del codice non gestito dal codice awaitable corregge questo errore. Una tecnica di separazione consiste nel creare un nuovo metodo per il codice non gestito e quindi chiamarlo dal codice awaitable. Ad esempio:

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