Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#事件和线程_C#_.net_Events - Fatal编程技术网

C#事件和线程

C#事件和线程,c#,.net,events,C#,.net,Events,示例程序:侦听某个文件夹上的文件系统事件,并在计时器事件触发时将文件系统事件信息打印到控制台 class Program { public static string location = @"D:\TestEvents"; public static double interval = 15000; public static System.Timers.Timer timer; public static List<string> listOf

示例程序:侦听某个文件夹上的文件系统事件,并在计时器事件触发时将文件系统事件信息打印到控制台

class Program
{
    public static string location = @"D:\TestEvents";
    public static double interval = 15000; 

    public static System.Timers.Timer timer;
    public static List<string> listOfChanges = new List<string>();

    static void Main(string[] args)
    {
        StartWatch();
        StartTimer();

        Console.ReadLine();
    }

    private static void StartWatch()
    {
        FileSystemWatcher Watcher = new FileSystemWatcher();
        Watcher.Path = location;
        Watcher.Created += new FileSystemEventHandler(OnFileCreatedOrDeleted);
        Watcher.Deleted += new FileSystemEventHandler(OnFileCreatedOrDeleted);
        Watcher.EnableRaisingEvents = true;
    }

    static void OnFileCreatedOrDeleted(object sender, FileSystemEventArgs e)
    {
        listOfChanges.Add(String.Format("Change Type: {0}, Name: {1}, Time: {2}", e.ChangeType, e.Name, DateTime.Now));
    }

    private static void StartTimer()
    {
        timer = new System.Timers.Timer();
        timer.AutoReset = false;
        timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimerEpleased);
        timer.Interval = interval;
        timer.Start();
    }

    private static void OnTimerEpleased(object sender, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("Timer event fired: " + DateTime.Now);
        foreach (var item in listOfChanges)
        {
            Console.WriteLine(item);
        }
        Console.WriteLine();
        listOfChanges.Clear();

        timer.Interval = interval;
        timer.Start();
    }
}

泛型列表不是线程安全的。当遍历listOfChanges(在OnTimeReplease中)时,可能会出现错误,并且新条目会将条目添加到列表中(OnFileCreatedOrDeleted)。看见您可以同步对列表的访问,也可以使用内置的线程安全集合:

我不确定FileSystemWatcher是否使用多个线程,但为了安全起见,请将对列表的访问包装为

lock (listOfChanges)
{
    //Code that reads or writes to the listOfChanges.
}

您不应该假设这些事件处理程序将从单个线程调用。FileSystemWatcher和Timer的文档都没有提到这些处理程序是如何被调用的,因此我在这里选择安全的方法,并确保我自己对该列表的访问是同步的

lock (listOfChanges)
{
    //Code that reads or writes to the listOfChanges.
}