C#窗体程序运行时间显示及线程的使用和MethodInvoker

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 w00窗体程序运行时间显示
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DateTime G_Datetime = DateTime.Now;
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    TimeSpan timeSpan = DateTime.Now - G_Datetime;
                    //MethodInvoker不带参数的委托,用来访问控件
                    //MethodInvoker,用于跨线程访问,它是一个委托,允许调用者将方法返回到UI线程(处理用户界面事件的线程)中,跨线程执行应用程序非常重要
                    //MethodInvoker,当需要执行一些较长时间运行的任务时,我们通常会创建一个新的工作线程,然而在完成任务后,我们必须将结果返回到ui线程中,以便更新用户界面,
                    //这就是MethodInvoker的作用,
                    //主要功能就是,将调用的方法,返回到UI线程中,确保线程安全,在ui线程中运行代码的好处是,它可以确保在用户界面上进行,所有的更改都得到正确的更新和呈现
                    Invoke((MethodInvoker)(() =>
                    {
                        label1.Text = $"系统已运行:{timeSpan.Days}天{timeSpan.Hours}时{timeSpan.Minutes}分{timeSpan.Seconds}秒";
                        /*string.Format("系统已运行:{0}天{1}时{2}分{3}秒",timeSpan.Days,timeSpan.Hours,timeSpan.Minutes,timeSpan.Seconds);*/
                    }));
                    Thread.Sleep(1000);
                }
            }
            );
            thread.IsBackground = true;
            thread.Start();
        }
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值