C# WPF线程操作

时间:2022-07-23
本文章向大家介绍C# WPF线程操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

界面显示:

xaml:

<Window x:Class="WpfApp3.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:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Label Content="Label" Name="lblShow" HorizontalAlignment="Left" Margin="175,165,0,0" VerticalAlignment="Top"/>
        <Button Content="Button" Name="btnCtrl" Click="BtnCtrl_Click" HorizontalAlignment="Left" Margin="340,165,0,0" VerticalAlignment="Top" Width="75"/>

    </Grid>
</Window>

c#代码:

using System.Threading;
using System.Windows;

namespace WpfApp3
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            th = new Thread(labShowThread);
        }

        private void labShowThread()
        {
            Dispatcher.Invoke(() =>
            {
                lblShow.Content = "在线程中修改了标签值";
            });
            
        }

        Thread th;
        private void BtnCtrl_Click(object sender, RoutedEventArgs e)
        {
            th.Start();
        }
    }
}