在FileSystemWatcher事件

时间:2015-10-23 20:41:03

标签: c# wpf multithreading dispatcher

我试图通过FileSystemEvent接收图像到我的WPF窗口,然而,我无法访问窗口上的图像插槽,因为FileSystemEvent发生在不同的线程上。我已阅读使用调度程序和调用,但我没有尝试解决问题。这是我的代码:

    public MainWindow()
    {
        InitializeComponent();
        if(!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = directory;
        watcher.Filter = "*.jpg";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {

        // Specify what is done when a file is changed, created, or deleted.
        BitmapImage b=new BitmapImage();
        b.BeginInit();
        b.UriSource=new Uri(e.FullPath);
        b.EndInit();
        image1.Dispatcher.Invoke(() => image1.Source = b); //What goes here?
        //I have also tried Application.Current.Dispatcher.Invoke
    }

<Image x:Name="image1" Grid.Row="0" Grid.Column="0"/>

1 个答案:

答案 0 :(得分:1)

您需要调用b.Freeze()(在创建它的线程上)以使其可供其他线程使用。