C# Error CS1996 – Cannot await in the body of a lock statement

C# Error

CS1996 – Cannot await in the body of a lock statement

Reason for the Error & Solution

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;
        }
    }
}

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 that will be prone to deadlocks. Extracting the asynchronous code from the lock statement block will correct 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;
        }
    }
}