111,129
社区成员
发帖
与我相关
我的任务
分享using System;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var source = "C:\\publish"; //这两个路径应该自己修改一下
var target = "C:\\publish1";
Copy(new DirectoryInfo(source), new DirectoryInfo(target));
Console.WriteLine("................按任意键结束");
Console.ReadKey();
}
private static bool Copy(DirectoryInfo source, DirectoryInfo target)
{
if (target.Exists)
throw new IOException("target 已经存在。请删除目录,再开始测试。");
target.Create();
(from file in source.EnumerateFiles().AsParallel()
let targetFile = Path.Combine(target.FullName, file.Name)
select Copy(file, targetFile)).Count();
(from dir in source.EnumerateDirectories().AsParallel()
let targetPath = Path.Combine(target.FullName, dir.Name)
let targetDir = new DirectoryInfo(targetPath)
select Copy(dir, targetDir)).Count();
return true;
}
private static bool Copy(FileInfo source, string target)
{
Console.WriteLine(target);
source.CopyTo(target);
return true;
}
}
}
这里,有 .AsParallel() 就是并发多线程的,不写它则就是顺序的。因此你可以迅速地在“多线程、单线程”中进行切换。
一个任务未必就应该使用多线程来实现,因此你应该掌握迅速改变程序设计的能力。