异步更新ObservableCollection <t>会导致挂起,并且不会进行GUI更新</t>

时间:2011-09-01 16:16:50

标签: c# wpf multithreading observablecollection autoresetevent

我正在WPF中实现Tracert的可视版本(作为学习练习),其中结果将转到列表框中。问题是(1)绑定到tracertDataView的列表框没有更新,但(2)我的整个应用程序挂起。

我确信#2是一个线程问题,但我不确定如何纠正它(以正确的方式)。另外我不确定我更新/绑定“DoTrace”结果的技术是否正确。

以下是 App.xaml

中的数据源
<Window.Resources>
<CollectionViewSource 
          Source="{Binding Source={x:Static Application.Current}, Path=TracertResultNodes}"   
          x:Key="tracertDataView" />

</Window.Resources>

App.xaml.cs

public partial class App : Application
{
    private ObservableCollection<TracertNode> tracertResultNodes = new ObservableCollection<TracertNode>();

    public void AppStartup(object sender, StartupEventArgs e)
    {
          // NOTE: Load sample data does work correctly.. and displays on the screen.  
         //      subsequent updates do not display
        LoadSampleData();
    }

    private void LoadSampleData()
    {

         TracertResultNodes = new ObservableCollection<TracertNode>();

        TracertNode t = new TracertNode();
        t.Address = new System.Net.IPAddress(0x2414188f);
        t.RoundTripTime = 30;
        t.Status = System.Net.NetworkInformation.IPStatus.BadRoute;

            TracertResultNodes.Add(t);
    }

    public ObservableCollection<TracertNode> TracertResultNodes
    {
        get { return this.tracertResultNodes; }
        set { this.tracertResultNodes = value; }
    }
}

以下是 MainWindow 代码

  public partial class MainWindow : Window
{
    CollectionViewSource tracertDataView;
    TraceWrapper _tracertWrapper = null;

    public MainWindow()
    {
        InitializeComponent();
         _tracertWrapper = new TraceWrapper();

        tracertDataView = (CollectionViewSource)(this.Resources["tracertDataView"]);
    }

    private void DoTrace_Click(object sender, RoutedEventArgs e)
    {
       ((App)Application.Current).TracertResultNodes = _tracertWrapper.Results;

       _tracertWrapper.DoTrace("8.8.8.8", 30, 50);
    }
}

FYI内部实现实例对象“traceWrapper.DoTrace”的详细信息

    /// <summary>
    /// Trace a host.  Note that this object internally calls the Async implementation of .NET's PING. 
    // It works perfectly fine in a CMD host, but not in WPF
    /// </summary>
     public ObservableCollection<TracertNode> DoTrace(string HostOrIP, int maxHops, int TimeOut)
    {
        tracert = new Tracert();

        // The following is triggered for every host that is found, or upon timeout
         //  (up to 30 times by default)
        AutoResetEvent wait = new AutoResetEvent(false);
       tracert.waiter = wait;

        tracert.HostNameOrAddress = HostOrIP;

        tracert.Trace();

        this.Results = tracert.NodeList;

        while (tracert.IsDone == false)
        {
            wait.WaitOne();
            IsDone = tracert.IsDone;
        }
        return tracert.NodeList;
    }

3 个答案:

答案 0 :(得分:2)

我不明白你如何使用AutoResetEvent,我想它不应该以这种方式使用:)

但是由于Trace已经在另一个线程中运行,你确定没有事件&#34; OnTracertComplete&#34;或者你的Tracert课程中有类似的东西?

如果没有,为什么你不将DispatchTimer放入你的应用程序? 该计时器将定期轮询直到tracert.IsDone变为真。 如果阻止执行应用程序线程直到操作完成,则会阻止窗口事件循环的执行,因此窗口永远不会更新。

另一个重要的事情是:你无法从另一个线程更新ObservableCollections。 注意并确保WPF窗口中更新的所有内容都是从窗口的同一个线程执行的。不知道你的Trace类究竟做了什么,但你的问题似乎当然是等待循环,在GUI应用程序中没有用。

使用通知事件或计时器轮询结果。对于这个特定的实现,具有1秒分辨率的计时器对我来说似乎很好,而且inpact的性能绝对是最小的。

如果您能够修改Tracert类,这是一种可能的实现。

    public delegate void TracertCallbacHandler(Tracert sender, TracertNode newNode);

    public class Tracert
    {
        public event TracertCallbacHandler NewNodeFound;
        public event EventHandler TracertCompleted;

        public void Trace()
        {
            ....
        }

        // This function gets called in tracert thread\async method.
        private void FunctionCalledInThreadWhenPingCompletes(TracertNode newNode)
        {
            var handler = this.NewNodeFound;
            if (handler != null)
                handler(this, newNode);
        }

        // This function gets called in tracert thread\async methods when everything ends.
        private void FunctionCalledWhenEverythingDone()
        {
            var handler = this.TracertCompleted;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

    }

以下是运行tracert的代码, 这是TracertWrapper。

    // Keep the observable collection as a field.
    private ObservableCollection<TracertNode> pTracertNodes;

    // Keep the instance of the running tracert as a field, we need it.
    private Tracert pTracert;

    public bool IsTracertRunning
    {
        get { return this.pTracert != null; }
    }

    public ObservableCollection<TracertNode> DoTrace(string hostOrIP, int maxHops, int timeOut)
    {
        // If we are not already running a tracert...
        if (this.pTracert == null)
        {
            // Clear or creates the list of tracert nodes.
            if (this.pTracertNodes == null)
                this.pTracertNodes = new ObservableCollection<TracertNode>();
            else
                this.pTracertNodes.Clear();

            var tracert = new Tracert();
            tracert.HostNameOrAddress = hostOrIP;
            tracert.MaxHops = maxHops;
            tracert.TimeOut = timeOut;

            tracert.NewNodeFound += delegate(Tracert sender, TracertNode newNode)
            {
                // This method is called inside Tracert thread.
                // We need to use synchronization context to execute this method in our main window thread.

                SynchronizationContext.Current.Post(delegate(object state)
                {
                    // This method is called inside window thread.
                    this.OnTracertNodeFound(this.pTracertNodes, newNode);
                }, null);
            };

            tracert.TracertCompleted += delegate(object sender, EventArgs e)
            {
                // This method is called inside Tracert thread.
                // We need to use synchronization context to execute this method in our main window thread.

                SynchronizationContext.Current.Post(delegate(object state)
                {
                    // This method is called inside window thread.
                    this.OnTracertCompleted();
                }, null);
            };

            tracert.Trace();

            this.pTracert = tracert;
        }

        return this.pTracertNodes;
    }

    protected virtual void OnTracertCompleted()
    {
        // Remove tracert object,
        // we need this to let the garbage collector being able to release that objects.
        // We need also to allow another traceroute since the previous one completed.
        this.pTracert = null;

        System.Windows.MessageBox.Show("TraceRoute completed!");
    }

    protected virtual void OnTracertNodeFound(ObservableCollection<TracertNode> collection, TracertNode newNode)
    {
        // Add our tracert node.
        collection.Add(newNode);
    }

答案 1 :(得分:1)

  

问题是列表框不仅没有更新,而且整个应用程序都挂起了。

这可能是由于AutoResetEvent中的DoTrace阻止造成的。你明确地在事件句柄上调用了Wait.WaitOne();,但据我所知,从来没有Set()它。一旦您拨打Wait.WaitOne(),这将导致应用程序永久挂起。

听起来tracert.Trace()是一种异步方法。是否包含某种形式的回调/事件,以便在完成后通知您?如果是这样,你应该使用它,而不是循环轮询,以确定它何时完成。

答案 2 :(得分:1)

  

(1)绑定到tracertDataView的列表框未更新

您不会看到列表框的更新,因为您要将新集合分配给TracertResultNodes属性,在这种情况下绑定根本不起作用,因为已分配新集合。

除了确保集合在下面Salvatore概述的同一个线程中更新之外,您应该只添加或删除现有集合中的项目,而不是分配由DoTrace函数生成的新项目。

private void DoTrace_Click(object sender, RoutedEventArgs e)
    {
       foreach(var traceNode in _tracertWrapper.Results)
       {
          ((App)Application.Current).TracertResultNodes.Add(traceNode);
       }

       _tracertWrapper.DoTrace("8.8.8.8", 30, 50);
    }

如果你确实分配了一个新的,那么你需要在你的App类上实现INotifyPropertyChanged,我不知道如何(或者是否)可以工作(我之前没有尝试过)。