C# 异步IO

异步IO

首先IO是什么?

IO:是input和output 的缩写,就是输入和输出

那异步IO又是什么?

程序不因为IO调用而被阻塞,就可以说程序是异步的。

异步IO的好处:

如果IO请求需要大量时间执行的话,异步文件IO方式可以显著提高效率,因为在线程等待的这段时间内,CPU将会调度其他线程进行执行,如果没有其他线程需要执行的话,这段时间将会浪费掉(可能会调度操作系统的零页线程)。

什么情况不应该使用异步IO?

IO请求操作很快的时候

C# 中异步IO的使用

1.异步写文件:


     
        static void WriteFlie(string FileName,string message)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("等级:{0}\n","IV");
            builder.AppendFormat("类型:{0}\n","erro");
            builder.AppendFormat("时间:{0}\n", DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss.fff"));
            builder.AppendFormat("信息:{0}\n", message);
           



            const int maxsize = 100000;
            ThreadPool.SetMaxThreads(1000, 1000);
            PrintMessage("主线程开始执行");

            // 初始化FileStream对象
            FileStream filestream = new FileStream(FileName+".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 100, true);

            //打印文件流打开的方式
            Console.WriteLine("文件流打开方式是否为异步{0}", filestream.IsAsync ? "是" : "否");

            byte[] writebytes = new byte[maxsize];
            string writemessage = builder.ToString();
            writebytes = Encoding.Unicode.GetBytes(writemessage);
            Console.WriteLine("信息大小: {0} 字节(byte)\n", writebytes.Length);
            // 调用异步写入方法比信息写入到文件中
            filestream.BeginWrite(writebytes, 0, writebytes.Length, new AsyncCallback(EndWriteCallback), filestream);
            filestream.Flush();
        }

        // 当把数据写入文件完成后调用此方法来结束异步写操作
        private static void EndWriteCallback(IAsyncResult asyncResult)
        {
            Thread.Sleep(500);
            PrintMessage("异步方法启动");

            FileStream filestream = asyncResult.AsyncState as FileStream;

            // 结束异步写入数据
            filestream.EndWrite(asyncResult);
            filestream.Close();
        }

        // 打印线程池信息
        private static void PrintMessage(String data)
        {
            int workthreadnumber;
            int iothreadnumber;

            // 获得线程池中可用的线程,把获得的可用工作者线程数量赋给workthreadnumber变量
            // 获得的可用I/O线程数量给iothreadnumber变量
            ThreadPool.GetAvailableThreads(out workthreadnumber, out iothreadnumber);

            Console.WriteLine("{0}\n 当前线程ID: {1}\n 当前线程是否是后台线程 :{2}\n 工作线程数:{3}\n IO线程数: {4}\n",
                data,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsBackground.ToString(),
                workthreadnumber.ToString(),
                iothreadnumber.ToString());
        }

输出结果:
在这里插入图片描述

异步读取文件

 const int maxsize = 1024;
        static byte[] readbytes = new byte[maxsize];
        static void Main(string[] args)
        {
            WriteFlie("test", "测试异步读写文件");
            ThreadPool.SetMaxThreads(1000, 1000);
            PrintMessage("主线程开始执行");

            // 初始化FileStream对象
            FileStream filestream = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 100, false);

            // 异步读取文件内容
            filestream.BeginRead(readbytes, 0, readbytes.Length, new AsyncCallback(EndReadCallback), filestream);
            Console.Read();
        }

        private static void EndReadCallback(IAsyncResult asyncResult)
        {
            Thread.Sleep(1000);
            PrintMessage("异步方法启动");

            // 把AsyncResult.AsyncState转换为State对象
            FileStream readstream = (FileStream)asyncResult.AsyncState;
            int readlength = readstream.EndRead(asyncResult);
            if (readlength <= 0)
            {
                Console.WriteLine("读取错误");
                return;
            }

            string readmessage = Encoding.Unicode.GetString(readbytes, 0, readlength);
            Console.WriteLine("读出的数据为 :\n" + readmessage);
            readstream.Close();
        }

       

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

或与且与或非

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值