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

l46*_*kok 79 .net c# wpf datagrid multithreading

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

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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

Bot*_*000 178

您可以使用

Dispatcher.Invoke(Delegate, object[])

Application(或任何UIElement)调度员.

您可以使用它,例如:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
Run Code Online (Sandbox Code Playgroud)

要么

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
Run Code Online (Sandbox Code Playgroud)

  • @l46kok 这可能有不同的原因(控制台应用程序、winforms 托管等)。正如@WolfgangZiegler 所说,您可以使用任何 UIElement。我通常只是使用“Application.Current”,因为它对我来说看起来更干净。 (2认同)

Eli*_*bel 40

最好的方法是SynchronizationContext从UI线程获取并使用它.此类将编组调用抽象到其他线程,并使测试更容易(与Dispatcher直接使用WPF相反).例如:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该提到 `_syncContext.Post(o =>` 是一个异步的“即发即忘”。要进行同步调用,应该使用 `_syncContext.Send(o =>` )。 (4认同)

Vin*_*ary 7

使用[Dispatcher.Invoke(DispatcherPriority,?Delegate)]从另一个线程或后台更改 UI。

第 1 步。使用以下命名空间

using System.Windows;
using System.Threading;
using System.Windows.Threading;
Run Code Online (Sandbox Code Playgroud)

第 2 步。将以下行放在您需要更新 UI 的位置

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));
Run Code Online (Sandbox Code Playgroud)

句法

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)
Run Code Online (Sandbox Code Playgroud)

参数

priority

类型: System.Windows.Threading.DispatcherPriority

优先级,相对于 Dispatcher 事件队列中的其他挂起操作,指定的方法被调用。

method

类型: System.Delegate

一个不带参数的方法的委托,它被推送到 Dispatcher 事件队列。

返回值

类型: System.Object

被调用的委托的返回值,如果委托没有返回值,则为 null。

版本信息

自 .NET Framework 3.0 起可用