掌握C#中的GUI多线程技巧:WinForms和WPF实例详解

**概述:**本指南详细解释了在C#中如何在创建控件的线程以外的线程中访问GUI。基础功能使用`Control.Invoke`(WinForms)或`Dispatcher.Invoke`(WPF),高级功能则利用`SynchronizationContext`实现线程间通信,确保代码清晰可读。

在C#中,要在创建控件的线程以外的线程访问控件,可以使用Control.Invoke(WinForms)或Dispatcher.Invoke(WPF)。以下是详细的步骤和示例代码,包括基础功能和高级功能。

在WinForms中访问控件:

基础功能:

  1. 创建WinForms应用程序: 创建一个包含按钮和标签的WinForms应用程序。
  2. 使用Invoke访问控件: 在另一个线程中使用Control.Invoke访问控件。

示例源代码:

复制代码
using System;
using System.Threading;
using System.Windows.Forms;

namespace WinFormsThreadedAccess
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnAccessControl_Click(object sender, EventArgs e)
        {
            // 在另一个线程中访问控件
            Thread thread = new Thread(AccessControl);
            thread.Start();
        }

        private void AccessControl()
        {
            if (lblStatus.InvokeRequired)
            {
                // 在UI线程上异步执行访问控件操作
                lblStatus.Invoke(new Action(() => lblStatus.Text = "控件已访问"));
            }
            else
            {
                // 在UI线程上直接访问控件
                lblStatus.Text = "控件已访问";
            }
        }
    }
}

在WPF中访问控件:

基础功能:

  1. 创建WPF应用程序: 创建一个包含按钮和标签的WPF应用程序。
  2. 使用Dispatcher访问控件: 在另一个线程中使用Dispatcher.Invoke访问控件。

示例源代码:

复制代码
using System;
using System.Threading;
using System.Windows;

namespace WPFThreadedAccess
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnAccessControl_Click(object sender, RoutedEventArgs e)
        {
            // 在另一个线程中访问控件
            Thread thread = new Thread(AccessControl);
            thread.Start();
        }

        private void AccessControl()
        {
            if (Dispatcher.CheckAccess())
            {
                // 在UI线程上直接访问控件
                lblStatus.Content = "控件已访问";
            }
            else
            {
                // 在UI线程上异步执行访问控件操作
                Dispatcher.Invoke(new Action(() => lblStatus.Content = "控件已访问"));
            }
        }
    }
}

高级功能:

在高级功能中,WinForms和WPF均可以使用SynchronizationContext进行线程间通信,代码更为简洁。

示例源代码:

复制代码
using System;
using System.Threading;
using System.Windows.Forms;

namespace AdvancedThreadedAccess
{
    public partial class MainForm : Form
    {
        private readonly SynchronizationContext synchronizationContext;

        public MainForm()
        {
            InitializeComponent();

            // 获取当前同步上下文
            synchronizationContext = SynchronizationContext.Current;
        }

        private void btnAccessControl_Click(object sender, EventArgs e)
        {
            // 在另一个线程中访问控件
            Thread thread = new Thread(AccessControl);
            thread.Start();
        }

        private void AccessControl()
        {
            // 在UI线程上异步执行访问控件操作
            synchronizationContext.Post(new SendOrPostCallback(UpdateLabel), "控件已访问");
        }

        private void UpdateLabel(object state)
        {
            // 在UI线程上更新标签文本
            lblStatus.Text = state.ToString();
        }
    }
}

在WPF中,Dispatcher本身就是一种同步上下文,所以高级功能的WPF示例代码与基础功能示例代码相似。

相关推荐
利威尔xu8 分钟前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
乌暮1 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis
不绝1912 小时前
Lua基础语法入门:注释、变量类型与字符串操作
开发语言·lua
Hhy_11072 小时前
《C++深度解构07》手撕 vector —— 从底层三指针架构到迭代器失效彻底吃透
c语言·开发语言·c++·学习·visual studio
风落青芜2 小时前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
艾莉丝努力练剑3 小时前
【QT】系统相关:TCP的API介绍
开发语言·前端·c++·人工智能·qt·学习·tcp/ip
BruceNeter3 小时前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
wuxianda10304 小时前
Swift 项目用 Xcode 脚手架起步:默认工程结构和依赖组合为什么会被识别成同源
开发语言·xcode·swift·4.3a·appstore审核
ShineWinsu4 小时前
对于Qt:QVBoxLayout常见属性以及方法的解析
开发语言·数据库·c++·qt·gui·客户端·布局管理器
Sarvartha5 小时前
反射综合案例:SQL 语句生成
java·开发语言