c# - 在线程中复制多个文件

标签 c# multithreading file asynchronous copy

我有以下情况,我必须复制多个(大约 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);
        }

因此,当文件在某个文件夹中创建并准备好使用时,我会一个接一个地复制该文件,但我需要在任何文件准备好使用时立即开始复制。所以我认为我应该使用线程。那么.. 如何实现并行复制?

@克里斯

检查文件是否准备好

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 是一个坏主意,只会减慢速度,因为机械磁头每次都需要旋转以寻找下一个读取位置(一个非常缓慢的过程),然后会被反弹轮到每个线程运行时。

坚持顺序方法并在单个线程中读取文件。

关于c# - 在线程中复制多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11029043/

相关文章:

c# - 为什么 System.Web.Hosting.ApplicationHost.CreateApplicationHost 抛出 System.IO.FileNotFoundException?

c# - C#如何获取Windows上运行的程序的名称

file - Lotus Notes - 从操作按钮打开文件

java - 为什么只有 1 个 java 源文件能够写入同一个文件?

ios - 从表中删除并删除文件

c# - 如何在统一的 XML 配置中将一个单例注册到不同的接口(interface)?

c# - 如何使用 NLog LogMessageGenerator 委托(delegate)?

Python 多处理文档示例

multithreading - 在函数式编程中如何避免副作用

java - 在Android中,什么线程可运行传递给Executors.newSingleThreadScheduledExecutor运行?