Compressing a stream asynchronously, and returning a byte[] Assuming I have to leave the contract intact (take byte[] and return byte[]), what's the correct way to structure this asynchronous method?

Will this deadlock running in ASP.NET in a web server thread?

public async Task&lt;byte[]&gt; CompressAsync(byte[] buffer)
{
    using (var outStream = new MemoryStream())
    {
        using (var tinyStream = new GZipStream(outStream, CompressionMode.Compress))
        using (var stream = new MemoryStream(buffer))
        {
            await stream.CopyToAsync(tinyStream);
        }

        return outStream.ToArray();
    }            
}
I don't see any reason for the inner stream. Instead, you can just WriteAsync() the whole buffer directly into the (confusingly named) tinyStream.



Your code won't deadlock if used properly (i.e. asynchronously), but it will deadlock if someone synchronously waits for it (e.g. byte[] resultBuffer = CompressAsync(inputBuffer).Result;). To make sure this doesn't happen, add .ConfigureAwait(false) after every await.

You should do this for all your "library" code, that is code that doesn't need to run in the ASP.NET request context/GUI thread.



This method doesn't use any instance state. Why isn't it static?