WPF 委托刷新UI线程(System.InvalidOperationException: '调用线程无法访问此对象,因为另一个线程拥有该对象。')

跨线程调用UI控件时会出现无法访问对象的错误




用委托实现跨线程调用


调试结果:



Solution Explore:



MainWindow.xaml

<Window x:Class="委托刷新UI线程.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:委托刷新UI线程"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="100" WindowStyle="ToolWindow">
    <Grid Background="Gray">
        <TextBox Name="textBox" Width="70" Height="20"></TextBox>
    </Grid>
</Window>


MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 委托刷新UI线程
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private delegate void UpdateUIDelegate();

        public MainWindow()
        {
            InitializeComponent();

            UpdateUIThreadTest();
        }

        private void UpdateUIThreadTest()
        {
            var th = new Thread(ThreadUpdateUI);
            th.Start();
        }

        private void ThreadUpdateUI()
        {
            UpdateUIDelegate updateUIDelegate = new UpdateUIDelegate(UpdateUI);
            this.Dispatcher.Invoke(updateUIDelegate);
        }

        private void UpdateUI()
        {
            textBox.Text = "Refreshed.";
        }
    }
}



猜你喜欢

转载自blog.csdn.net/empty_android/article/details/79763086