共用方式為


編譯器錯誤 CS4004

無法在不安全的內容中等候

範例

下列範例會產生 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;
            }
        });
    }
}

此程式碼在 C# 13 中產生錯誤,因為 await 位於 unsafe 區塊中。

ReverseText 方法會以直覺方式使用背景工作,以指定字串的反向順序非同步建立新字串。

更正這個錯誤

將不安全的程式碼與可等候的程式碼分開,可更正此錯誤。 有一種分隔技術可針對不安全的程式碼建立新方法,然後從可等候的程式碼加以呼叫。 例如:

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