FileSystemWatcher Network Disconnect

后端 未结 3 846
盖世英雄少女心
盖世英雄少女心 2021-02-06 00:19

I have a FileSystemWatcher monitoring a file on a network share. If an event occurs to make the share unavailable, maybe due to a network problem, the FileSystemWatcher becomes

3条回答
  •  [愿得一人]
    2021-02-06 00:48

    Wouldn't something like this work? Seems to work for my simple test case.

    var fsw = new FileSystemWatcher("[folder]", "*.*") { IncludeSubdirectories = true};
    var fsw_processing = false;
    fsw.Deleted += (s, e) => 
    {
        fsw_processing = true;
        fsw.EnableRaisingEvents = false;
        //......
        fsw.EnableRaisingEvents = true;
        fsw_processing = false;
    };    
    fsw.Changed += (s, e) => 
    {
        fsw_processing = true;
        fsw.EnableRaisingEvents = false;
        //......
        fsw.EnableRaisingEvents = true;
        fsw_processing = false;
    };    
    //governor thread to check FileSystemWatcher is still connected. 
    //It seems to disconnects on network outages etc.
    Task.Run(() =>
    {
        while (true)
        {
            if (fsw.EnableRaisingEvents == false && fsw_processing == false)
            {                        
                try
                {fsw.EnableRaisingEvents = true;}
                catch (Exception) { fsw.EnableRaisingEvents = false; }            
            }
            System.Threading.Thread.Sleep(1000 * 10);//sleep 10 secs
        }
    });
    

提交回复
热议问题