Partager via


Erreur de compilateur CS1996

Impossible d’attendre dans le corps d’une instruction lock

Exemple

L’exemple suivant génère l’erreur CS1996 :

public class C
{
    private readonly Dictionary<string, string> keyValuePairs = new();

    public async Task<string> ReplaceValueAsync(string key, HttpClient httpClient)
    {
        lock (keyValuePairs)
        {
            var newValue = await httpClient.GetStringAsync(string.Empty);
            if (keyValuePairs.ContainsKey(key)) keyValuePairs[key] = newValue;
            else keyValuePairs.Add(key, newValue);
            return newValue;
        }
    }
}

Le code précédent génère la même erreur avec C# 13, comme le await dans le bloc d’instructions lock.

Pour corriger cette erreur

Le code asynchrone dans un bloc d’instructions lock est difficile à implémenter de manière fiable et encore plus difficile à implémenter dans un sens général. Le compilateur C# ne prend pas en charge cette opération pour éviter d’émettre du code susceptible de faire l’objet d’interblocages. L’extraction du code asynchrone du bloc d’instructions lock corrige cette erreur. Par exemple :

public class C
{
    private readonly Dictionary<string, string> keyValuePairs = new();

    public async Task<string> ReplaceValueAsync(string key, HttpClient httpClient)
    {
        var newValue = await httpClient.GetStringAsync(string.Empty);
        lock (keyValuePairs)
        {
            if (keyValuePairs.ContainsKey(key)) keyValuePairs[key] = newValue;
            else keyValuePairs.Add(key, newValue);
            return newValue;
        }
    }
}