Skip to content

用异步模式读取一个文件

🏷️ C# 学习

调用 FileStreamBeginReadEndRead 方法实现文件的异步模式读取。

代码示例

ReadFileClass.cs

点击查看代码
cs
using System;
using System.IO;
using System.Text;

namespace AsyncReadFile
{
    /// <summary>
    /// 打包传递给完成异步后回调的方法
    /// </summary>
    class ReadFileClass
    {
        /// <summary>
        /// 以便回调方法中释放异步读取的资源
        /// </summary>
        public FileStream _fs;
        /// <summary>
        /// 文件内容
        /// </summary>
        public Byte _data;

        public ReadFileClass(FileStream fs, Byte data)
        {
            _fs = fs;
            _data = data;
        }
    }
}

Program.cs

点击查看代码
cs
using System;
using System.IO;
using System.Text;
using System.Threading;

namespace AsyncReadFile
{
    class Program
    {
        const string _testFile = "TestAsyncRead.txt";

        static void Main(string args)
        {
            try
            {
                if (File.Exists(_testFile))
                {
                    File.Delete(_testFile);
                }
                using (FileStream fs = File.Create(_testFile))
                {
                    string content = "我是文件内容。";
                    byte contentbyte = Encoding.Default.GetBytes(content);
                    fs.Write(contentbyte, 0, contentbyte.Length);
                }
                using (FileStream fs = new FileStream(_testFile, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous))
                {
                    byte data = new byte[1024];
                    ReadFileClass rfc = new ReadFileClass(fs, data);
                    // 这里开始异步读取
                    IAsyncResult ir = fs.BeginRead(data, 0, 1024, FinishReading, rfc);
                    Thread.Sleep(3 * 1000);
                    Console.Read();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                try
                {
                    if (File.Exists(_testFile))
                    {
                        File.Delete(_testFile);
                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }

        /// <summary>
        /// 完成异步读取时调用的方法
        /// </summary>
        /// <param name="ir">状态对象</param>
        static void FinishReading(IAsyncResult ir)
        {
            ReadFileClass rfc = ir.AsyncState as ReadFileClass;
            // 这一步是必须的
            // 这会让异步读取占用的资源被释放
            int length = rfc._fs.EndRead(ir);
            Console.Write("读取文件结束。\r\n 文件的长度为: {0}\r\n 文件内容为:", length);
            byte result = new byte[length];
            Array.Copy(rfc._data, 0, result, 0, length);
            Console.WriteLine(Encoding.Default.GetString(result));
        }
    }
}