在WPF应用程序中,是否有可以分配给FileSystemWatcher.SynchronizingObject的对象?
我可以自己制作,但如果有可用,我想使用它。
答案 0 :(得分:5)
Reflector显示实现ISynchronizeInvoke
的唯一类(即FileSystemWatcher.SynchronizingObject
属性的类型)是System.Windows.Form.Control
(及其子类);似乎没有任何WPF对象实现此接口。
答案 1 :(得分:3)
您需要创建一个ISynchronizeInvoke对象,该对象从Window中包装System.Windows.Threading.Dispatcher实例。该类是WPF与ISynchronizeInvoke对象最接近的东西。
在包装器类中,只需将BeginInvoke调用转发给您已包装的调度程序。我做了一些额外的工作,还包装了DispatcherOperation,它来自Dispatcher.BeginInvoke方法,在ISynchronizeInvoke.EndInvoke方法中调用它的Wait方法。
到目前为止,一切似乎都正常工作,太糟糕了,微软认为让Dispatcher类实现界面易于使用是不合适的。
答案 2 :(得分:1)
有一种方法。启用事件时FileSystemWatcher(EnableRaisingEvents = true)创建自己的线程来监视FS事件。通过ISynchronizeInvoke,它可以异步调用Form的成员,例如,(它的线程可以异步与主线程交互 - UI线程)。
在WPF中没有ISynchronizeInvoke的实现,但是有可能 通过您的Window的Dispatched属性与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 :(得分: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
}