栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

.NET异步流读取/写入

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.NET异步流读取/写入

您将需要使用NetStream读取的回调来处理此问题。坦率地说,将复制逻辑包装到其自己的类中可能会更容易,以便您可以维护活动Streams的实例。

这是我的处理方式(未经测试):

public class Assignment1{    public static void NetToFile(NetworkStream net, FileStream file)     {        var copier = new AsyncStreamCopier(net, file);        copier.Start();    }    public static void NetToFile_Option2(NetworkStream net, FileStream file)     {        var completedEvent = new ManualResetEvent(false);        // copy as usual but listen for completion        var copier = new AsyncStreamCopier(net, file);        copier.Completed += (s, e) => completedEvent.Set();        copier.Start();        completedEvent.WaitOne();    }    /// <summary>    /// The Async Copier class reads the input Stream Async and writes Synchronously    /// </summary>    public class AsyncStreamCopier    {        public event EventHandler Completed;        private readonly Stream input;        private readonly Stream output;        private byte[] buffer = new byte[4096];        public AsyncStreamCopier(Stream input, Stream output)        { this.input = input; this.output = output;        }        public void Start()        { GetNextChunk();        }        private void GetNextChunk()        { input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null);        }        private void InputReadComplete(IAsyncResult ar)        { // input read asynchronously completed int bytesRead = input.EndRead(ar); if (bytesRead == 0) {     RaiseCompleted();     return; } // write synchronously output.Write(buffer, 0, bytesRead); // get next GetNextChunk();        }        private void RaiseCompleted()        { if (Completed != null) {     Completed(this, EventArgs.Empty); }        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408364.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号