gpt4 book ai didi

c# - 异步文件和文件夹复制 - C#

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:37 25 4
gpt4 key购买 nike

我有一种方法可以将一个目录中的所有文件和文件夹复制到另一个目录,并且它是递归工作的。我的问题是它阻塞了主线程,我想让文件和文件夹的实际复制异步进行。我目前正在使用一个函数来异步复制文件,但它似乎不起作用。这是代码:

private async void copyEverything(string source, string target)
{
// Variable to hold the attributes of a file
FileAttributes attributes;

// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(source);
DirectoryInfo[] dirs = dir.GetDirectories();

if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: " + source);
}

// If the destination directory doesn't exist, create it.
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}

// Loop through for all files in a directory
foreach (string filename in Directory.EnumerateFiles(source))
{
if (!File.Exists(targetFolder + filename.Substring(filename.LastIndexOf('\\'))))
{
attributes = File.GetAttributes(filename);

if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
//System.Windows.MessageBox.Show("File {" + filename + "} is READ ONLY");
}
else
{
try
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(target + filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
filesRemaining--;
}
}
}
catch (UnauthorizedAccessException)
{
}
}
}
}

// Loop through each subdirectory in the current directory and recursively call the
// copyEverything() method using the subdirectory's full name and the name of the
// target folder plus the subdirectory folder name
foreach (DirectoryInfo subdir in dirs)
{
foldersRemaining--;
string temppath = System.IO.Path.Combine(target, subdir.Name);
copyEverything(subdir.FullName, temppath);
}
}

有什么办法可以让它在不阻塞主线程的情况下工作吗?

最佳答案

你仍然在主线程上做一堆 IO:Directory.ExistFile.Exist 等...您可能希望避免在主线程上执行所有操作。

因此,一个简单的解决方案是添加一个新方法:

private void copyEverythingAsync(string source, string target)
{
Task.Run(()=> copyEverything(source, target));
}

然后从 copyEverything 方法中删除 async/await

这会将操作从 ThreadPool 转移到一个新线程上,而不会阻塞您的主线程。

关于c# - 异步文件和文件夹复制 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com