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

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

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

委托定义:委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用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++;
            }
        }
    }
}

效果:

原文地址:https://www.cnblogs.com/swjian/p/9471211.html