Azure Function app best practice for deadlock avoidance with 3rd party library

Viewed 30

I have a C# Azure Function app that is called via an http trigger. This is called very frequently. As execution counts increase, we experience deadlocks and the app service effectively crashes. The offending code is where we authenticate the incoming http requests, using the Argon2 library (https://github.com/kmaragon/Konscious.Security.Cryptography).

Azure slow request monitoring detected the function executions where taking a long time, specifically with this issue:

165 threads are calling Task.Result and synchronously waiting on a Task object. The caller function identified for the maximum number of threads is Konscious.Security.Cryptography.Argon2.GetBytes

Examination of the GetBytes method reveals:

public override byte[] GetBytes(int bc)
        {
            ValidateParameters(bc);
            return Task.Run(async () => await GetBytesAsyncImpl(bc).ConfigureAwait(continueOnCapturedContext: false)).Result;
        }

MS recommends this:

It's usually a bad idea to block on async code by calling Task.Wait or Task.Result as this can easily lead to deadlocks. Please check the section Async all the way in the MSDN magazine on Async Best practices.

Therefore I expect this way of calling GetBytes to be appropriate?

public static Task<byte[]> HashPassword(string password, byte[] salt)
{
    var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password))
    {
        Salt = salt,
        DegreeOfParallelism = 1234,
        Iterations = 1234,
        MemorySize = 512 // Kb
    };

    return Task.FromResult(argon2.GetBytes(16));
}

Is this a recommended way of handling this problem (i.e. async all the way). Are there any pitfalls I may unintentionally be falling into this this approach?

1 Answers

I have found there is an async Argon method:

public Task<byte[]> GetBytesAsync(int bc)
{
    ValidateParameters(bc);
    return GetBytesAsyncImpl(bc);
}

so have gone "async all the way" as the top level Azure function app is async.

Related