在C/S架构中,不管是传统的winform还是wpf都可能会遇到进行异步操作文件的时候。文件小还好说,直接写操作代码。
如果是大文件很多时候做成异步的操作。在界面上显示一个进度条什么的,后台使用一个backgroundworker来做。在这里告诉大家在.NET Framework4.5中支持异步IO的操作。大大简化之前些的异步方法代码。
使用backgroundworker代码
复制代码 代码如下:
View Code
private void Button_Click_3(object sender, RoutedEventArgs e)
{
System.ComponentModel.BackgroundWorker bak = new System.ComponentModel.BackgroundWorker();
bak.DoWork += bak_DoWork;
bak.RunWorkerCompleted += bak_RunWorkerCompleted;
bak.RunWorkerAsync();
}
void bak_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
string sourceDir = @"E:/";
string endDir = @"F:/";
foreach (string filename in Directory.EnumerateFiles(sourceDir))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(endDir + filename.Substring(filename.LastIndexOf('//'))))
{
SourceStream.CopyTo(DestinationStream);
}
}
}
}
void bak_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
MessageBox.Show("ok");
}
复制代码 代码如下:
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
string sourceDir = @"E:/";
string endDir = @"F:/";
foreach (string filename in Directory.EnumerateFiles(sourceDir))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(endDir + filename.Substring(filename.LastIndexOf('//'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
MessageBox.Show("ok");
}
新闻热点
疑难解答
图片精选