在WPF中安全地访问UI(主)线程

在WPF中安全地访问UI(主)线程

我有一个应用程序,每次我正在观看的日志文件更新时都会更新我的数据网格(附加新文本),方法如下:

private void DGAddRow(string name, FunctionType ft)
    {
                ASCIIEncoding ascii = new ASCIIEncoding();

    CommDGDataSource ds = new CommDGDataSource();

    int position = 0;
    string[] data_split = ft.Data.Split(' ');
    foreach (AttributeType at in ft.Types)
    {
        if (at.IsAddress)
        {

            ds.Source = HexString2Ascii(data_split[position]);
            ds.Destination = HexString2Ascii(data_split[position+1]);
            break;
        }
        else
        {
            position += at.Size;
        }
    }
    ds.Protocol = name;
    ds.Number = rowCount;
    ds.Data = ft.Data;
    ds.Time = ft.Time;

    dataGridRows.Add(ds); 

    rowCount++;
    }
    ...
    private void FileSystemWatcher()
    {
        FileSystemWatcher watcher = new FileSystemWatcher(Environment.CurrentDirectory);
        watcher.Filter = syslogPath;
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
            | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Changed += new FileSystemEventHandler(watcher_Changed);
        watcher.EnableRaisingEvents = true;
    }

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        if (File.Exists(syslogPath))
        {
            string line = GetLine(syslogPath,currentLine);
            foreach (CommRuleParser crp in crpList)
            {
                FunctionType ft = new FunctionType();
                if (crp.ParseLine(line, out ft))
                {
                    DGAddRow(crp.Protocol, ft);
                }
            }
            currentLine++;
        }
        else
            MessageBox.Show(UIConstant.COMM_SYSLOG_NON_EXIST_WARNING);
    }

当为FileWatcher引发事件时,因为它创建了一个单独的线程,当我尝试运行dataGridRows.Add(ds)时; 要添加新行,程序只会在调试模式下没有任何警告的情况下崩溃。

在Winforms中,这可以通过使用Invoke函数轻松解决,但我不知道如何在WPF中进行此操作。


慕桂英3389331
浏览 1412回答 3
3回答

aluckdog

您可以使用Dispatcher.Invoke(Delegate, object[])在Application(或任何UIElement)调度员。您可以使用它,例如:Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));要么someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
打开App,查看更多内容
随时随地看视频慕课网APP