2008-10-31 75 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

相關問題