FileSystemWatcher + Dialog

0 c# multithreading

我想在每次更改某个文件时显示一个对话框......但每次出现该对话框时,我的应用程序都会冻结.我怎么能用另一个线程做到这一点?有任何想法吗?

protected virtual void CreateWatcher (object path)
{
    if (watcher != null)
    {
        watcher.EnableRaisingEvents = false;
        watcher.Dispose ();
    }

    //Create a new FileSystemWatcher. 
    watcher = new FileSystemWatcher ();

    //Set the filter to only catch TXT files. 
    watcher.Filter = "*.txt";
    watcher.IncludeSubdirectories = true;
    watcher.NotifyFilter = NotifyFilters.LastWrite;

    //Subscribe to the Created event.
    watcher.Changed += new FileSystemEventHandler (OnChanged);
    watcher.Created += new FileSystemEventHandler (OnChanged);
    //watcher.Deleted += new FileSystemEventHandler (OnChanged);
    //watcher.Renamed += new RenamedEventHandler (OnRenamed);

    //Set the path to C:\\Temp\\ 
    watcher.Path = @path.ToString();

    //Enable the FileSystemWatcher events. 
    watcher.EnableRaisingEvents = true;
}
void OnChanged (object source, FileSystemEventArgs e)
{
    NovaInteracaoMsg();
    }

protected virtual void NovaInteracaoMsg ()
{
    novaInteracao = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.YesNo, "Foi detectada a mudança nos arquivos do modelo. Deseja inserir uma nova interação?");
    ResponseType result = (ResponseType)novaInteracao.Run ();

    if (result == ResponseType.Yes) {
        OpenInfoWindow (novaInteracaoPath);
        return;
    }
    else {
        novaInteracao.Destroy ();
    }
}

void OnRenamed (object source, RenamedEventArgs e)
{
    //Console.WriteLine ("File: {0} renamed to\n{1}", e.OldFullPath, e.FullPath);
    }

protected virtual void OpenInfoWindow (string path)
{
    ModMemory.Iteration iterWin = new ModMemory.Iteration (path);
    iterWin.Modal = true;
    iterWin.Show ();

    iterWin.Destroyed += delegate {
        // TODO: Funções para executar quando a janela for fechada
        // Possivelmente atualizar o número de interações realizadas
        Console.WriteLine ("Janela modal destruída");           
    };
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

问题是你已经在使用另一个线程了.请尝试以下方法之一

  1. 设置FileSystemWatcher.SynchronizingObject属性,以便在UI线程上引发事件.现在,您可以显示不会冻结的UI或
  2. 使用Control.BeginInvoke()在事件处理程序.

这是一次心理调试尝试,你的问题中没有任何内容可以帮助我确定这是正确的答案.