Sdílet prostřednictvím


Chyba kompilátoru CS4004

Nelze očekávat v nebezpečném kontextu.

Příklad

Následující ukázka vygeneruje 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;
            }
        });
    }
}

Tento kód vygeneruje chybu v jazyce C# 13, protože await je v unsafe bloku.

Metoda ReverseText naively používá úlohu na pozadí k asynchronnímu vytvoření nového řetězce v obráceném pořadí daného řetězce.

Oprava této chyby

Oddělení nebezpečného kódu od očekávaného kódu opraví tuto chybu. Jednou z technik oddělení je vytvoření nové metody pro nebezpečný kód a jeho následné volání z očekávaného kódu. Příklad:

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