Compiler Error CS1996
Cannot await in the body of a lock statement
Example
The following sample generates 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;
}
}
}
The preceding code produces the same error with C# 13, as the await
is in the lock
statement block.
To correct this error
Asynchronous code within a lock
statement block is hard to implement reliably and even harder to implement in a general sense. The C# compiler doesn't support doing this to avoid emitting code prone to deadlocks. Extracting the asynchronous code from the lock
statement block corrects this error. For example:
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;
}
}
}
Συνεργαστείτε μαζί μας στο GitHub
Μπορείτε να βρείτε την πηγή για αυτό το περιεχόμενο στο GitHub, όπου μπορείτε επίσης να δημιουργήσετε και να εξετάσετε ζητήματα και αιτήματα έλξης. Για περισσότερες πληροφορίες, ανατρέξτε στον οδηγό συνεργατών.