开发者

Incorporate multi-threading for FileSystemWatcher Service

开发者 https://www.devze.com 2023-04-01 12:49 出处:网络
When I receive a notification from a FileSystemWatcher, I want to start a separate thread to take care of the further processing.

When I receive a notification from a FileSystemWatcher, I want to start a separate thread to take care of the further processing.

How do I go about doing Mul开发者_如何学Goti-Threading in the FileSystemWatcher Service for Event-Handling ?


I don't understand why people were unable to answer this simple question. For any other people wondering about this, here is one way of doing this:

class Program
{
    static void Main(string[] args)
    {
        FileSystemWatcher fsw = new FileSystemWatcher();
        fsw.Path = @"C:\temp\";
        fsw.Created += new FileSystemEventHandler(onCreatedFile);
        fsw.EnableRaisingEvents = true;

        Console.ReadLine();
    }

    private static void onCreatedFile(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("Thread " + AppDomain.GetCurrentThreadId() + " detected " + e.FullPath);

        Thread t = new Thread(new ParameterizedThreadStart(seperateThread));
        t.Start(e);
    }

    private static void seperateThread(object obj)
    {
        FileSystemEventArgs e = (FileSystemEventArgs)obj;

        Console.WriteLine("Thread " + AppDomain.GetCurrentThreadId() + " detected " + e.FullPath);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消