正文

异步io的一个例子2007-09-21 16:15:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/jixian/29576.html

分享到:

//异步io的一个例子, 不明白???? 异步为什么那样复杂,以及异步io的步骤。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace _5_10
{
    public class filereader
    {
        const string path = "E:\\1.txt";

        public void synccall()        //同步的
        {
            FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read,1024,false);
            int x = 0;
            while ((x = fs.ReadByte())!= -1) { }
            fs.Close();
            Console.WriteLine("synchro open finished "+DateTime.Now);
        }

        public void asynccall()    //异步的
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
            worddocstate state = new worddocstate();
            state.fs = fs;
            state.content = new byte[fs.Length];
            state.resetevent = new AutoResetEvent(false);
            AsyncCallback readdoccallback = new AsyncCallback(ReadDocCallback);
            fs.BeginRead(state.content,0,(int)state.fs.Length,ReadDocCallback,state);
            state.resetevent.WaitOne();
            Console.WriteLine("async open finished "+DateTime.Now);

        }

        private void ReadDocCallback(IAsyncResult asyncresult)
        {
            worddocstate state = (worddocstate)asyncresult.AsyncState;
            FileStream stream = state.fs;
            int bytesread = stream.EndRead(asyncresult);
            stream.Close();
            state.resetevent.Set();
        }

        public class worddocstate
        {
            public FileStream fs;
            public byte[] content;
            public AutoResetEvent resetevent;
        }

 

        static void Main(string[] args)
        {
            filereader fr = new filereader();
          
            fr.synccall();
            fr.asynccall();
        }
    }
}

阅读(2262) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册