using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
//文件异步操作
namespace FileAsynchronousOperation
{
class Program
{
static void Main(string[] args)
{
//实例化MyFile类
MyFile myFile = new MyFile();
//定义参数
string filePath = "D:\testasy.txt";
string msg = "helloworld";
//调用异步操作方法
myFile.AsynchronousOperation(filePath,msg);
}
}
/// <summary>
/// 文件
/// </summary>
class MyFile
{
/// <summary>
/// 文件异步操作
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="msg">写入内容</param>
public void AsynchronousOperation(string filePath,string msg)
{
FileStream fileSteam = null;
FileInfo fileinfo = new FileInfo(filePath);
//判断文件是否存在
if (!fileinfo.Exists)
{
fileSteam = fileinfo.Create();
Console.WriteLine("创建文件{0}", filePath);
fileSteam.Close();
}
fileSteam = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.None, 4096, true);
Console.WriteLine("开启异步操作{0}", fileSteam.IsAsync);
byte[] buffer = Encoding.Default.GetBytes(msg);
//开始执行异步操作
IAsyncResult asynncResult = fileSteam.BeginWrite(buffer,0, buffer.Length, new AsyncCallback(EndWriteCallBack), fileSteam);
Console.WriteLine("开始异步写入请稍候...");
Console.Read();
}
/// <summary>
/// 回调函数
/// </summary>
/// <param name="asyncResult">状态</param>
public void EndWriteCallBack(IAsyncResult asyncResult)
{
Console.WriteLine("异步写入开始...");
FileStream stream = asyncResult.AsyncState as FileStream;//转化为FileStream类型
if (stream!=null)
{
stream.EndWrite(asyncResult);
stream.Close();
}
Console.WriteLine("写入完成");
}
}
}
Filestreom 在对文件进行异步操作时,对大数据量读写操作使用 BeginRead 和 Begin 树 rite 方法的效果更好;
而对于数据量较少的读写操作,使川异步方式的速度可能会比同步方式要慢。
所以,你需要针对应用程序的实际情况决定是否要选择异步处理方式。