WPF Task.Run ==>线程无法访问此对象

时间:2019-05-17 20:45:27

标签: c# task invoke dispatcher

我在主窗体中有3个用户控件,并且在Ctor主窗体中创建了所有用户控件。问题是我在Tasktor中运行了Ctor Monitoring,它的工作正常,但是当我更改usercontrol(Page)并返回到Monitoring时Ctor Monitoring中的页面task.run无法正常工作,但是当我使用Dispatcher.Invoke时,所有代码都可以正常工作,但是Ui处于冻结状态。

主要形式:         //页数         PageHome ph;         PageMonitoring pm;         PageAboutus pa;

    public FrmMain(string userName, string password)
    {
        InitializeComponent();

        HomeLoadOfflineHelper.HomeLoadOffline(userName, password);

        txbUserName = userName;

        ph = new PageHome(userName, password);
        pm = new PageMonitoring();
        pa = new PageAboutus();

        DataContext = this;
    }

监视ctor:

    public PageMonitoring()
    {
        InitializeComponent();
        InitializeNetworkInterface();

        Task.Run(() =>
        {

            short Counter = 0;

            LessPingSeries = new ChartValues<ObservableValue> { };
            NormalPingSeries = new ChartValues<ObservableValue> { };
            DownloadSeries = new ChartValues<ObservableValue> { };
            UploadSeries = new ChartValues<ObservableValue> { };

            while (true)
            {
                Thread.Sleep(2000);

                MessageBox.Show("OK");

                using (Ping ping = new Ping())
                {
                    LessPingSeries.Add(new ObservableValue(ping.Send("8.8.8.8").RoundtripTime));
                    NormalPingSeries.Add(new ObservableValue(ping.Send("4.2.2.4").RoundtripTime));
                }

                DownloadSeries.Add(new ObservableValue(ByteSize.FromBytes(bytesReceivedSpeed).MegaBytes));
                UploadSeries.Add(new ObservableValue(ByteSize.FromBytes(bytesSentSpeed).MegaBytes));

                Counter++;
                if (Counter >= 5)
                {
                    LessPingSeries.RemoveAt(0);
                    NormalPingSeries.RemoveAt(0);

                    DownloadSeries.RemoveAt(0);
                    UploadSeries.RemoveAt(0);

                    Counter--;
                }

                Application.Current.Dispatcher.Invoke(() =>
                {
                    UpdateNetworkInterface();
                });
            }
        });

        DataContext = this;
    }

0 个答案:

没有答案