lev*_*evi 4 c# multithreading asynchronous copy file
我有以下场景,我要复制多个(大约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);
}
Run Code Online (Sandbox Code Playgroud)
因此,当文件在某个文件夹中创建并且可以使用时,我会一个接一个地复制该文件,但是我需要在任何文件准备就绪后立即开始复制.所以我认为我应该使用Threads.那么.. 如何实现并行复制?
@克里斯
检查文件是否准备好
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Tud*_*dor 11
从机械磁盘执行并行I/O是一个坏主意,只会减慢速度,因为机械磁头每次需要旋转以寻找下一个读取位置(一个非常慢的过程),然后在每个线程中反弹轮到跑了.
坚持顺序方法并在单个线程中读取文件.
| 归档时间: |
|
| 查看次数: |
4892 次 |
| 最近记录: |