侧面多线程中的SystemFileWatcher无法正常工作

时间:2016-04-07 14:47:30

标签: c# multithreading file-watcher

我正在尝试观察连接到我的电脑的所有USB存储设备中的文件发生的变化。要做到这一点,我写了一个c#控制台应用程序,但它不起作用只给一个空白屏幕。请有人帮我做这个

    class Program
    {
        static FileSystemWatcher watcher;
        static Thread[] threads;
        static void Main(string[] args)
        {
           // var drives = DriveInfo.GetDrives();
            DriveInfo[] drives = DriveInfo.GetDrives();
            for (int i = 0; i < drives.Length; i++)
            {
                var drive = drives[i];
                if (drive.DriveType == DriveType.Removable && isDirectoryEmpty(drive.Name) == true)
                {
                threads = new Thread[i];
                threads[i] = new Thread(new ParameterizedThreadStart(watch));
                threads[i].Start(drive.Name);
                }

            }
            foreach (Thread t in threads)
            {
                t.Start();
            }

        }
        static bool isDirectoryEmpty(string path)
        {
            if (!Directory.Exists(path)) return false;
            return Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Any();
        }
        static void watch(object pth)
        {
            string path = (string)pth;

            watcher = new FileSystemWatcher();

            watcher.Path = path;//assigning path to be watched
            watcher.EnableRaisingEvents = true;//make sure watcher will raise event in case of change in folder.
            watcher.IncludeSubdirectories = true;//make sure watcher will look into subfolders as well.
            watcher.Filter = "*.*"; //watcher should monitor all types of file.


            watcher.Created += watcher_Created;//register event to be called when a file is created in specified path
            watcher.Changed += watcher_Changed;//register event to be called when a file is updated in specified path
            watcher.Deleted += watcher_Deleted;//register event to be called when a file is deleted in specified path


            //while (true) ;
        }

        static void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            watcher.EnableRaisingEvents = true;
            Console.WriteLine("File : " + e.FullPath + " is deleted.");
            watcher.EnableRaisingEvents = true;
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
              if (Directory.Exists(e.FullPath))
                {
                    watch(e.FullPath);
                }
                else
                {
                    Console.WriteLine("File : " + e.FullPath + " is updated.");

                        try
                        {
                            if (!string.IsNullOrEmpty(e.FullPath))
                            {
                                watcher.EnableRaisingEvents = false;
                                File.Delete(e.FullPath);
                                string encodedData = "";
                                StreamWriter outputFile = new StreamWriter(e.FullPath, false);

                                    outputFile.Write(encodedData);
                                    outputFile.Flush();
                                    outputFile.Close();

                                watcher.EnableRaisingEvents = true;
                                //break;

                            }

                        }
                        catch (Exception excep)
                        {
                            Console.WriteLine(excep.Message.ToString());
                            Thread.Sleep(1000);
                        }


                }
   }

        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is created.");




        }
}

1 个答案:

答案 0 :(得分:1)

我发现的关键问题是控制台在启动线程后立即退出(因此,而不是Q)

线程启动两次..一次使用参数,一次只使用.start

线程数组对我来说根本不起作用,代码崩溃了。所以我把它作为一个列表并添加了新的线程。

我删除了&#34;更改&#34;处理所以没有别的东西搞砸了 - 毕竟目标是让一个工作的观察者在一个线程中

好的,这是非常简化但是这段代码可以工作 - 我一直在攻击你的代码,直到它工作 - 代码不是生产代码,它不整洁,它最终不会清除线程等等等等。

public static void getImageFullUrl(final Context context, String url, ImageView imgView, int radius, int margin) {
    instance = appSingleton.getInstance(context);
    instance.getPicasso()
            .load(url)
            .fit()
            .centerCrop()
            .tag("Request")
            .transform(new RoundedTransformation((int) Util.convertPixelsToDp(radius, context),
                    (int) Util.convertPixelsToDp(margin, context))) // TODO Reuse RoundedTransform
            .into(imgView);
}

按要求添加输出:

输入:Input

输出:Output