在WPF访问UI(主)线程安全 [英] Accessing UI (Main) Thread safely in WPF

查看:202
本文介绍了在WPF访问UI(主)线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我看得到更新日志文件以下列方式(追加新的文字)每次用于更新我的DataGrid的应用程序:

I have an application which updates my datagrid each time a log file that I'm watching gets updated (Appended with new text) in the following manner:

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);添加新行,该方案只是没有崩溃在调试模式给予任何警告。

When the event is raised for the FileWatcher, because it creates a separate thread, when I try to run dataGridRows.Add(ds); to add the new row, the program just crashes without any warning given during debug mode.

在的WinForms,这很容易被利用调用函数解决,但我不知道如何去这上头。

In Winforms, this was easily solved by utilizing the Invoke function but I am not sure how to go about this in WPF.

推荐答案

您可以使用

Dispatcher.Invoke(委派,对象[])

应用程序的(或任何的UIElement 的)调度。

on the Application's (or any UIElement's) dispatcher.

您可以使用它,例如是这样的:

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

这篇关于在WPF访问UI(主)线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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