2008-10-31 72 views

回答

5

反射器显示实现ISynchronizeInvoke(即,FileSystemWatcher.SynchronizingObject属性的类型)的唯一类是System.Windows.Form.Control(及其子类);似乎没有任何实现此接口的WPF对象。

1

有一种方法。当您启用事件(EnableRaisingEvents = true)时,FileSystemWatcher创建它自己的线程来监视FS事件。通过ISynchronizeInvoke它可以异步调用你的Form的成员,例如(它的线程可以异步与主线程交互 - UI线程)。

在WPF中有没有ISynchronizeInvoke的执行,但有一个可能性 与UI线程交互,通过这样的窗口调度属性:

var fsw = new FileSystemWatcher() 
{ 
    //Setting the properties: Path, Filter, NotifyFilter, etc. 
}; 

fsw.Created += (sender, e) => 
{ 
    Dispatcher.Invoke(new Action<params_types>((params_identifiers) => 
     { 
      //here the code wich interacts with your IU elements 
     }), here_params); 
}; 


//... in this way (via Dispatcher.Invoke) with the rest of events 

fsw.EnableRaisingEvents = true; 
3

您需要创建一个包装了ISynchronizeInvoke对象Window中的System.Windows.Threading.Dispatcher实例。该类是WPF最接近ISynchronizeInvoke对象的类。

在包装类中,只需将BeginInvoke调用转发给您包装的调度程序。我做了一些额外的工作,还包装了Dispatcher.BeginInvoke方法生成的DispatcherOperation,以在ISynchronizeInvoke.EndInvoke方法内调用Wait方法。

到目前为止,一切似乎都正常工作,这太糟糕了微软没有看到适合让Dispatcher类实现接口以方便使用。

0

使用DispatcherTimer而不是系统计时器。 这对WPF来说工作得很好。

DispatcherTimer t1 = new DispatcherTimer(); 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     t1.Interval = new TimeSpan(0,0,0,0,200); 
     t1.Tick += new EventHandler(t1_Tick); 
     t1.Start(); 
    ... 
    void t1_Tick(object sender, EventArgs e) 
    { 

     //some work 

    } 
+0

这是无题吗? – ygoe 2018-01-17 17:43:30

相关问题