线程介绍

复制代码
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.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {

            timer1.Enabled = true;
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Thread childThread = new Thread(childref);
            childThread.Start();
        }
        public void CallToChildThread()
        {
            while (true)
            {
                Console.WriteLine("子线程开始");
                // 线程暂停 3000 毫秒
                int sleepfor = 1000;
                Console.WriteLine("子线程等待 {0} 秒", sleepfor / 1000);
                Thread.Sleep(sleepfor);
                SetText("我是子线程:" + DateTime.Now.ToString());
            }
        }
        private delegate void SetTextCallback(string text);

        /// <summary>
        /// 给label赋值
        /// </summary>
        /// <param name="text"></param>
        private void SetText(string text)
        {
            // InvokeRequired需要比较调用线程ID和创建线程ID
            // 如果它们不相同则返回true
            if (this.label1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.label1.Text = text;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
             if (progressBar1.Value<progressBar1.Maximum)
            {
                progressBar1.Value++;
            }
            else
            {
                
                timer1.Enabled = false;
            }
        }
    }
}
复制代码

 

posted @   .NET_海  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示