在 MVC 4 应用程序中,我有一个将文件复制到目标文件夹的任务。因为我有多个文件,所以我为每个文件创建一个任务,我想等到它们都完成。问题是我的代码块Task.WaitAll(copyingTasks.ToArray())
好像任务永远不会结束,所以它永远不会通过那行代码。下面是示例代码:
private void CopyFilesFromWorkingCopyForProject(string projectName)
{
var copyingTasks = new List<Task>
{
CopyAllFromDirectoryToDirectory(FilesUtils.AndroidConfigsPath(), FilesUtils.AndroidPathForProject(projectName)),
CopyAllFromDirectoryToDirectory(FilesUtils.AndroidValuesPath(), FilesUtils.AndroidPathForProject(projectName)),
CopyFileToDirectory(FilesUtils.AndroidManifestPath(), FilesUtils.AndroidPathForProject(projectName)),
CopyAllFromDirectoryToDirectory(FilesUtils.IosConfigsPath(), FilesUtils.IosPathForProject(projectName))
};
Task.WaitAll(copyingTasks.ToArray());
}
private async Task CopyAllFromDirectoryToDirectory(string sourceDirectory, string destinationDirectory)
{
foreach (string filename in Directory.EnumerateFiles(sourceDirectory))
{
await CopyFileToDirectory(filename, destinationDirectory);
}
}
private async Task CopyFileToDirectory(string filename, string destinationDirectory)
{
using (FileStream sourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream destinationStream = File.Create(destinationDirectory + filename.Substring(filename.LastIndexOf('\\'))))
{
await sourceStream.CopyToAsync(destinationStream);
}
}
}
如果我评论 Task.WaitAll(copyingTasks.ToArray());
它不再阻塞,但我想等待所有文件被复制。