AsyncStreamCopier類(NetworkComms 2.3.1源碼瞭解和學習)

來源:互聯網
上載者:User

標籤:

networkComms.net2.3.1開源版本,基於gpl V3協議。因為不能公開3.x版本的源碼,所以基於此版本進行學習。3.X版本進行了諸多改進和Bug修複,使用方法上兩者相差不大。/*請注意使用以下代碼,需遵循GplV3協議*/using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Threading;namespace DPSBase{         public class AsyncStreamCopier    {        /// <summary>         /// 拷貝資料完成 觸發的事件        /// </summary>        public event EventHandler Completed;        private byte[] buffer = new byte[4096];               public AsyncStreamCopier()        {                                }        /// <summary>         ///開始一個非同步資料拷貝        /// </summary>              public void Start(Stream input, Stream output)        {            GetNextChunk(new Stream[] { input, output });        }        private void GetNextChunk(Stream[] streams)        {            var input = streams[0];            //把Stream[0] 中的輸入資料流中的資料讀取到buffer中,當buffer中的資料讀取完成後,觸發InputReadComplete方法            input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, streams);        }        private void InputReadComplete(IAsyncResult ar)        {            var streams = ar.AsyncState as Stream[];            var input = streams[0];            var output = streams[1];                      //等待掛起的非同步讀取完成。             int bytesRead = input.EndRead(ar);                        if (bytesRead == 0)            {                RaiseCompleted();                return;            }            //  同步寫入            output.Write(buffer, 0, bytesRead);            //  讀取下一資料區塊            GetNextChunk(streams);        }        private void RaiseCompleted()        {            if (Completed != null)            {                Completed(this, EventArgs.Empty);            }        }              public static void CopyStreamTo(Stream source, Stream destination)        {            //號誌-預設無訊號  來進程不得通行            var completedEvent = new ManualResetEvent(false);            // copy as usual but listen for completion            var copier = new AsyncStreamCopier();            //一旦完成,給訊號            copier.Completed += (s, e) => completedEvent.Set();            //開始拷貝資料,如果拷貝資料完成,觸發號誌            copier.Start(source, destination);            //有交警 需要訊號 否則等待            completedEvent.WaitOne();        }    }} http://www.cnblogs.com/networkcommshttp://www.networkcoms.cn 編輯

 

AsyncStreamCopier類(NetworkComms 2.3.1源碼瞭解和學習)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.