c#中如何跨线程调用windows窗体控件?

本文介绍了一个使用C#实现的Windows窗体应用程序中如何进行线程操作。通过定义委托并使用线程安全的方法更新UI元素,展示了如何创建后台线程并在主线程与子线程间安全地交互。

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;  //线程操作引用的命名空间

namespace windowform线程操作
{


    public delegate void RunDele();//定义一个委托,没有参数
    public partial class Form1 : Form
    {

        Thread thread;     //造一个线程对象
        public Form1()
        {
            InitializeComponent();

           // Control.CheckForIllegalCrossThreadCalls = false;  //告诉程序不要检查线程的安全性,比较省力,但会对程序造成不好影响
        }
        bool isRun = true;
        //点击启动
        private void button1_Click(object sender, EventArgs e)
        {
            thread = new Thread(new ThreadStart(Run));  

            thread.IsBackground = true;

            thread.Start();   //委托开始执行

           /*& button1.Enabled = false;
            long i = 0;
            while (isRun)
            {
                listView1.Items.Insert(0,i.ToString());

                i++;
            }

            isRun = true;*/
        }

        private void button2_Click(object sender, EventArgs e)
        {
            isRun = false;
            button1.Enabled = true ;
        }
        long i = 0;
        void Run()
        {
           // button1.Enabled = false;
        
            while (isRun)
            {
              
               RunDele();
           }

            isRun = true;
        }

        void RunDele()
        {
            if (listView1.InvokeRequired)
            {
                RunDele dr = new RunDele(RunDele);
                this.Invoke(dr);
            }
            else
            {
                listView1.Items.Insert(0, i.ToString());

                i++;
            }
        }
        void Exit()
        {
            listView1.Items.Insert(0, i.ToString());

            i++;
        }
    }
}

 

转载于:https://www.cnblogs.com/275147378abc/p/4615256.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值