Udostępnij za pośrednictwem


Błąd kompilatora CS4004

Nie można oczekiwać w niebezpiecznym kontekście

Przykład

Poniższy przykład generuje 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;
            }
        });
    }
}

Ten kod generuje błąd w języku C# 13, ponieważ await element znajduje się w unsafe bloku.

Metoda ReverseText naiwnie używa zadania w tle, aby asynchronicznie utworzyć nowy ciąg w odwrotnej kolejności danego ciągu.

Aby poprawić ten błąd

Oddzielenie niebezpiecznego kodu od oczekiwanego kodu poprawia ten błąd. Jedną z technik separacji jest utworzenie nowej metody dla niebezpiecznego kodu, a następnie wywołanie go z oczekiwanego kodu. Na przykład:

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