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;
}
}
}
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.