在一个线程中复制多个文件
本文关键字:复制 文件 线程 一个 | 更新日期: 2023-09-27 18:37:03
我有以下情况,我必须复制多个(大约 10,50,200,...)文件。我一个接一个地同步这样做。这是我的代码片段。
static void Main(string[] args)
{
string path = @"";
FileSystemWatcher listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
while (Console.ReadLine() != "exit") ;
}
public static void listener_Created(object sender, FileSystemEventArgs e)
{
while (!IsFileReady(e.FullPath)) ;
File.Copy(e.FullPath, @"D:'levani'FolderListenerTest'CopiedFilesFolder'" + e.Name);
}
因此,当在某个文件夹中创建文件并准备好使用时,我会一个接一个地复制该文件,但我需要在任何文件准备好使用后立即开始复制。所以我认为我应该使用线程。所以。。如何实现并行复制?
@Chris
检查文件是否已准备就绪
public static bool IsFileReady(String sFilename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
从机械磁盘进行并行 I/O 是一个坏主意,只会减慢速度,因为机械头每次都需要旋转以寻找下一个读取位置(一个非常缓慢的过程),然后随着每个线程轮到运行时被反弹。
坚持顺序方法并在单个线程中读取文件。
现在只有这个(@Tudor所说的),但是由于碎片化,并行复制文件会使硬盘驱动器变得混乱。 在我的应用程序中,我使用排队复制 200 个同时生成的文件,只是为了以"线性"方式将它们放在硬盘驱动器上。
您可以在此处阅读有关该主题的更多信息。
您可能有一个执行所有处理的Thread
,即
Queue files = new Queue();
static void Main(string[] args)
{
string path = @"";
FileSystemWatcher listener = new FileSystemWatcher(path);
Thread t = new Thread(new ThreadStart(ProcessFiles));
t.Start();
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
while (Console.ReadLine() != "exit") ;
}
public static void listener_Created(object sender, FileSystemEventArgs e)
{
files.Enqueue(e.FullPath);
}
void ProcessFiles()
{
while(true)
{
if(files.Count > 0)
{
String file = files.Dequeue();
while (!IsFileReady(file)) ;
File.Copy(file, @"D:'levani'FolderListenerTest'CopiedFilesFolder'" + file);
}
}
}
在listener
事件中,将文件名添加到队列中。
然后在您的Thread
中,您可以从队列中获取文件名并从那里进行处理。