我有一个应用程序,每当我正在查看的日志(log)文件以以下方式更新(附加了新文本)时,它就会更新我的数据网格:

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);
    }

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

在Winforms中,通过使用Invoke函数很容易解决这个问题,但我不确定如何在WPF中实现这一点.

推荐答案

你可以用

Dispatcher.Invoke(Delegate, object[])

Application号(或任何UIElement号)调度器上.

你可以用 it f或 example like this:

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

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

.net相关问答推荐

为什么DotNet新的webapi;命令会为我生成不同的文件夹

SLN配置文件:映射问题

MassTransit RespondAsync 无法返回空值

如何获取控制台应用程序的执行目录

Int32.ToString() 是特定于文化的吗?

C# 是否(或将)包含用于副作用验证的功能?

如何在 EF 代码优先中禁用链接表的级联删除?

如何退出所有正在运行的线程?

Convert.ToBoolean 和 Boolean.Parse 不接受 0 和 1

从 Windows 窗体打开 URL

.NET 中是否有可序列化的通用键/值对类?

非通用 TaskCompletionSource 或替代

String.Replace() 与 StringBuilder.Replace()

我应该绑定到 ICollectionView 还是 ObservableCollection

绑定到不在列表中的值的可编辑组合框

如何使用通用扩展方法中的字符串列名在 IQueryable 上应用 OrderBy?

MailMessage,Sender 和 From 属性的区别

如何从 HashSet 中检索实际项目?

System.Array.CopyTo() 和 System.Array.Clone() 之间的区别

在 C# 中转义无效的 XML 字符