wpf(怎么跨线程访问wpf控件)

时间:2023-03-09 01:53:55
wpf(怎么跨线程访问wpf控件)

在编写代码时,我们经常会碰到一些子线程中处理完的信息,需要通知另一个线程(我这边处理完了,该你了)。

但是当我们通知WPF的UI线程时需要用到Dispatcher。

首先我们需要想好在UI控件上需要显示什么内容。然后写一个显示UI内容的方法。

以下是代码

 private void UIThreaddosomething(string s)    //UI线程要做的事情
{
//do something //这里也可以做一些其他的事情
Label2.Content = s;
ellipse1.Fill=new SolidColorBrush(Colors.Red);
ellipse2.Fill=new SolidColorBrush(Colors.Red);
}

然后我们声明一个委托,由于UIThreaddosomething有一个字符串参数,所以声明的委托要与其保持一致

public delegate void RefleshUI(string s);

然后在创建一个方法,这个方法将通过委托将子线程与UI线程联系起来。

        private void delegatedosomething(string s)
{
ellipse1.Dispatcher.Invoke(new RefleshUI(UIThreaddosomething), s);
// ellipse2.Dispatcher.Invoke(new RefleshUI(UIThreaddosomething), s);
}

这里我之前以为只要UI控件里有多少控件,就需要在此方法里用多少个Dispatcher,最后发现是我太年轻,只需要一个控件用上Dispatcher就好啦。

这里我们就可以跨线程访问WPF的UI控件了

完整代码如下,(这里我们也还可以使用一个中间方法来调用了UI方法,这样当程序有多个UI方法时,我们可以在这个中间方法中做一些处理,然后决定引用那些UI方法)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
using System.Threading; namespace 子线程通知主线程做一些事情
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public delegate void RefleshUI(string s);
private void Button_Click(object sender, RoutedEventArgs e)
{
Thread th;
th = new Thread(fun);
th.IsBackground = true;
th.Start();
} private void fun(object obj)
{ //////做一些子线程该做的事情
/////
/////
/**子线程完成后通知UI线程*/
delegatedosomething("你好,我是jjp_god,我做完了");
}
private void delegatedosomething(string s)
{
ellipse1.Dispatcher.Invoke(new RefleshUI(dofun), s);
// ellipse2.Dispatcher.Invoke(new RefleshUI(UIThreaddosomething), s);
}
private void UIThreaddosomething(string s) //UI线程要做的事情
{
//do something //这里也可以做一些其他的事情
tb_show.Text = s;
Label2.Content = s;
ellipse1.Fill=new SolidColorBrush(Colors.Red);
ellipse2.Fill=new SolidColorBrush(Colors.Red);
}
private void dofun(string s)
{
UIThreaddosomething(s);
} }
}