patterncsharpMinor
Compressing a stream asynchronously, and returning a byte[]
Viewed 0 times
streambytereturningcompressingasynchronouslyand
Problem
Assuming I have to leave the contract intact (take
Will this deadlock running in ASP.NET in a web server thread?
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 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();
}
}Solution
I don't see any reason for the inner
Your code won't deadlock if used properly (i.e. asynchronously), but it will deadlock if someone synchronously waits for it (e.g.
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
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?Context
StackExchange Code Review Q#69809, answer score: 2
Revisions (0)
No revisions yet.