Napomena
Pristup ovoj stranici zahteva autorizaciju. Možete pokušati da se prijavite ili da promenite direktorijume.
Pristup ovoj stranici zahteva autorizaciju. Možete pokušati da promenite direktorijume.
Cannot await in an unsafe context
The following sample generates 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;
}
});
}
}
This code generates an error in C# 13 because the await
is in the unsafe
block.
The ReverseText
method naively uses a background task to asynchronously create a new string in reverse order of a given string.
Separating the unsafe code from the awaitable code corrects this error. One separation technique is creating a new method for the unsafe code and then calling it from the awaitable code. For example:
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;
}
}
}
Povratne informacije za .NET
.NET je projekat otvorenog koda. Izaberite vezu da biste pružili povratne informacije: