在WPF應用程序中,是否有可以分配給FileSystemWatcher.SynchronizingObject的對象?在WPF應用程序中,是否有可以分配給FileSystemWatcher.SynchronizingObject的對象?
我可以做我自己的,但如果有一個可用,我想使用它。
在WPF應用程序中,是否有可以分配給FileSystemWatcher.SynchronizingObject的對象?在WPF應用程序中,是否有可以分配給FileSystemWatcher.SynchronizingObject的對象?
我可以做我自己的,但如果有一個可用,我想使用它。
反射器顯示實現ISynchronizeInvoke
(即,FileSystemWatcher.SynchronizingObject
屬性的類型)的唯一類是System.Windows.Form.Control
(及其子類);似乎沒有任何實現此接口的WPF對象。
有一種方法。當您啓用事件(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;
您需要創建一個包裝了ISynchronizeInvoke對象Window中的System.Windows.Threading.Dispatcher實例。該類是WPF最接近ISynchronizeInvoke對象的類。
在包裝類中,只需將BeginInvoke調用轉發給您包裝的調度程序。我做了一些額外的工作,還包裝了Dispatcher.BeginInvoke方法生成的DispatcherOperation,以在ISynchronizeInvoke.EndInvoke方法內調用Wait方法。
到目前爲止,一切似乎都正常工作,這太糟糕了微軟沒有看到適合讓Dispatcher類實現接口以方便使用。
使用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
}
這是無題嗎? – ygoe 2018-01-17 17:43:30