FileWatcher - NullObjectReference

时间:2014-09-07 09:13:38

标签: c# asp.net

我正在创建FileWatcher,我将watcher_Changed方法添加为事件 一段时间后,它在catch部分崩溃为 NullReferenceObject (IIS Express错误)。

private static void watcher_Changed(object sender, FileSystemEventArgs e)
{
    try
    {
        fWatcher.EnableRaisingEvents = false;
        System.Threading.Thread.Sleep(300);
        var newLoc = ReadLines();
        var context = GlobalHost.ConnectionManager.GetHubContext<MyHub1>();
        //Do something
        fWatcher.EnableRaisingEvents = true;
    }
    catch(Exception err)
    {
//Error appears here
        fWatcher.EnableRaisingEvents = false;
        fWatcher = null;
        fWatcher.Dispose();
        fWatcher = new FileSystemWatcher();
        while (fWatcher.EnableRaisingEvents != true)
        {
            try
            {
                fWatcher.EnableRaisingEvents = true;
            }
            catch(Exception exc)
            {                    
                System.Threading.Thread.Sleep(100);
            }

        }

    } 
}

我该如何解决?

1 个答案:

答案 0 :(得分:0)

  fWatcher = null;    //You cannot do this "fWatcher." after this line 
                      //(Until you call fWatcher = new FileSystemWatcher() at least)
  fWatcher.Dispose(); //You cannot do this !!!!!

如果要处置它,请先调用Dispose()然后再创建一个新的。 您不能在对象上调用方法