简体   繁体   中英

In target framework 4.5, WPF Dispatcher.Invoke is not allowing to update the Text Block in separate thread

Following method is from mainwindow , which calls the method Show() in the sub window . I used Dispatcher.Invoke thread to update the labels in the sub window untill the device search is done, which is working good upto target framework 3.5 and not working in 4.5 framework

private void OnShowBTWindow(bool isSrchDev)
        {
            BTMeasure winBTMeasure = new BTMeasure();
            winBTMeasure.Owner = this;
            if (!isSrchDev)
            {
                winBTMeasure.ShowDialog();
            }
            else {
                **winBTMeasure.Show(this);**
                if (AvailableDevices != null)
                {
                    winBTMeasure = null;
                    winBTMeasure = new BTMeasure();
                    winBTMeasure.Owner = this;
                    winBTMeasure.ShowDeviceListWindow(this);
                }
            }
        }

Following method is from sub window, which updates the text block in sub window until the device search is completed the window will be appearing which may take 2 seconds to find the devices. Once the DeviceSearch() is true, the sub window will be closed. This code is working good upto target framework 3.5 but not working in the target framework 4.5

public void Show(Window owner)
        {
            try
            {
                this.Owner = owner;
                this.Dispatcher.Invoke((Action)(() =>
                {
                    txtHeader.Visibility = System.Windows.Visibility.Hidden;
                    txtbody.Text = "Searching for the device..!!";
                    btnCancel.Visibility = System.Windows.Visibility.Hidden;
                    btnSearchCont.Visibility = System.Windows.Visibility.Hidden;
                    this.Show();
                }));
                if (DeviceSearch())
                {
                    this.Close();
                }
            }
       }

Please help provide input in fixing this issue.

You should be more specific about what "this issue" is.

That said, I see you are calling "this.Close()" outside of the anonymous method invoked by Dispatcher.Invoke(). Like other GUI object members, that has to be executed on the dispatcher thread as well.

For that matter, I'm not entirely sure it's safe to set the Owner property outside the dispatcher thread. In general, you really should work hard to avoid any access of a thread-affinitied object outside that object's owning thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM