GZipStream does not call underlying streams *Async methods when destination of CopyToAsync

大憨熊 提交于 2019-12-12 05:38:39

问题


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:


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).



来源:https://stackoverflow.com/questions/40285243/gzipstream-does-not-call-underlying-streams-async-methods-when-destination-of-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!