次の方法で共有


コンパイラ エラー CS4004

unsafe コンテキストで待機することはできません

次の例では 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;
            }
        });
    }
}

このコードでは、awaitunsafe ブロック内にあるため、C# 13 でエラーが生成されます。

ReverseText メソッドは、単純にバックグラウンド タスクを使用して、指定した文字列の逆の順序で新しい文字列を非同期的に作成します。

このエラーを解決するには

待機可能なコードからアンマネージド コードを分離すると、このエラーを修正できます。 分離する手法の 1 つは、アンセーフ コード用の新しいメソッドを作成し、待機可能なコードからそれを呼び出すことです。 次に例を示します。

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