FileSystemWatcher和GUI [英] FileSystemWatcher and GUI

查看:48
本文介绍了FileSystemWatcher和GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WPF项目和FileSystemWatcher类有一些问题. 在我的MainWindow类中,当在UI中单击按钮启动"时,观察者开始观察文件夹. 一切正常,没有任何问题-创建文件时,观察者可以正确识别. 但是,当观察者正在等待时,用户无法在UI中执行任何操作. nexample应该可以单击停止...".

I have a little problem with my WPF project and the FileSystemWatcher class. In my MainWindow class the watcher begins to watch a folder when Button Start is clicked in the UI. Everything works without any problems - the watcher recognizes correctly when a file is created. But while watcher is waiting it is not possible for user to do anything in the UI. It should be possible for nexample to click Stop...

 private void Start_Click(object sender, RoutedEventArgs e)
    {
        rdbTextBox.Document.Blocks.Clear();
        Start.IsEnabled = false;
        rdbTextBox.Document.Blocks.Add(new Paragraph(new Run("Test gestarte-Warte auf Befund....")));
        Stop.IsEnabled = true;

        watcher = new FileSystemWatcher(ConfigSettings.Default.FilePath); 

        // Only watch text files.
        // watcher.Filter = "*.bef";
        watcher.Filter = "*.txt";
        // Add event handlers.          
        watcher.Created += OnCreated;
        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait until new file in folder
        watcher.WaitForChanged(System.IO.WatcherChangeTypes.Created);           
        watcher.Dispose();

        // Parse letter
        edifactLetter = parser.ParseDocument(ConfigSettings.Default.FilePath + "\\" + fileName);
        // Validate Letter
        edifactVal.Validate(edifactLetter);

        writeResults();
        Start.IsEnabled = true;           
    }

    private void OnCreated(object sender, FileSystemEventArgs e)
    {   
        FileInfo file = new FileInfo(e.FullPath);
        fileName = file.Name;
    }

有人可以向我解释我在做什么错吗? 谢谢!

Can anyone explain me what I am doing wrong? Thanks!

推荐答案

这是因为WaitForChanged()不是异步方法,而是同步的.这意味着如果您在UI线程中使用它,它将被阻止.

This is because WaitForChanged() is not an asynchronous method, it is synchronous. Meaning if you are using that in your UI thread it will get blocked.

请参见此处: https://msdn. microsoft.com/en-us/library/67220zhk(v=vs.110).aspx

我建议您可以为OnChanged事件创建一个事件处理程序,然后执行所需的操作.

I suggest that you could create an event handler for the OnChanged event and then do what you need to do.

这篇关于FileSystemWatcher和GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆