Errore del compilatore CS4004
Non è possibile attendere in un contesto non sicuro
Esempio
L'esempio seguente genera l'errore 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;
}
});
}
}
Questo codice genera un errore in C# 13 perché await
si trova nel blocco unsafe
.
Il metodo ReverseText
usa in modo nativo un'attività in background per creare in modo asincrono una nuova stringa in ordine inverso di una determinata stringa.
Per correggere l'errore
La separazione del codice non gestito dal codice awaitable corregge questo errore. Una tecnica di separazione consiste nel creare un nuovo metodo per il codice non gestito e quindi chiamarlo dal codice awaitable. Ad esempio:
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;
}
}
}
Collabora con noi su GitHub
L'origine di questo contenuto è disponibile in GitHub, in cui è anche possibile creare ed esaminare i problemi e le richieste pull. Per ulteriori informazioni, vedere la guida per i collaboratori.