GZipStream does not call underlying streams *Async

2019-09-05 04:41发布

Using the following construct for a GZipStream it never seems to call the *Async method of my custom stream when GZipStream is the destination of CopyToAsync.

using (var fs = new System.IO.FileStream(@"C:\BTR\Source\Assemblies\BTR.Rbl.Evolution.Documents.dll", 
        System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, 8192, true))
{
    using (var ss = new GZipStream(new MyCustomStream(), CompressionMode.Compress))
    {
        await fs.CopyToAsync(ss);
    }
}

It seems to only call the BeginWrite/EndWrite mechanisms. Is there a way to derive from GZipStream to make it call WriteAsync instead so that my custom stream doesn't have to implement both the WriteAsync method along with the BeginWrite/EndWrite methods?

You can find a working sample of this here

Update: Callstack when initial Write() method called

SampleStream.Write(buffer, offset, count)
System.IO.Compression.DeflateStream.DoMaintenance(array, offset, count)
System.IO.Compression.DeflateStream.InternalWrite(array, offset, count, isAsync)
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(msg, replySink)
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(o)
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(state)
System.Threading.ExecutionContext.RunInternal(executionContext, callback, state, preserveSyncCtx)
System.Threading.ExecutionContext.Run(executionContext, callback, state, preserveSyncCtx)
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
(Unmanaged code)

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-05 05:30

It would be more correct for your custom stream to implement BeginWrite/EndWrite (and BeginRead/EndRead as well). It's not hard if you use my AsyncEx.Tasks library:

public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count,
    AsyncCallback callback, object state)
{
  var task = WriteAsync(buffer, offset, count);
  return ApmAsyncFactory.ToBegin(task, callback, state);
}

public override void EndWrite(IAsyncResult asyncResult)
{
  ApmAsyncFactory.ToEnd(asyncResult);
}

(ApmAsyncFactory has been added to the 1.2.0-alpha-01 version of AsyncEx.Tasks).

查看更多
登录 后发表回答