C# 线程中使用delegate对控件进行操作

本文介绍了一种在线程中安全更新UI控件的方法,通过定义委托来改变控件的值,避免了直接在线程中修改UI控件导致的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果在线程中想改变控件的值是不可以的,会报出以下错误。

那么,如何在线程中改变控件上的值呢?第一个想到的就是委托。

委托定义:委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。(来自于百度百科)

首先定义委托,让其改变控件值

delegate void UpText(string text);

然后在线程中实例出委托

UpText up = delegate (string text)
{
       textBox1.Text = text;
};

最后更改调用其委托方法

this.Invoke(up, new object[] { i.ToString() });

完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        delegate void UpText(string text);

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread th = new Thread(Test);
            th.IsBackground = true;
            th.Start();
        }

        void Test()
        {
            UpText up = delegate (string text)
            {
                textBox1.Text = text;
            };

            int i = 0;
            while(true)
            {
                this.Invoke(up, new object[] { i.ToString() });
                i++;
            }
        }
    }
}

效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值