我对线程入门理解

本文介绍了一种在Windows窗体中使LABEL控件实时显示系统时间的方法。通过创建后台线程并利用Sleep函数定时更新LABEL文本,实现了LABEL与系统时间的同步。此方案避免了频繁触发事件导致的性能问题。

之前有个朋友问我在windows窗体上拖一个LABEL,然后在窗体加载后,取当前时间给它,这样为什么不能让LABEL和系统的时间同步变化。实现这个其实有两种方法,有非常简单的是用Timer控件。然而,一直没有用过线程,找了点资料还是可以实现的:

 

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

namespace WindowsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

private void Form3_Load(object sender, EventArgs e)
{
System.Threading.ThreadStart time
= new System.Threading.ThreadStart(TimeStart);
System.Threading.Thread th1
= new System.Threading.Thread(time);
//添加这个属性才可以实现跨控件使用进程
Control.CheckForIllegalCrossThreadCalls = false;
th1.Start();
System.Threading.Thread.Sleep(
1000);

}


private void TimeStart()
{
while (!false)
{
//让当前进程休眠一秒再显示LABEL
System.Threading.Thread.Sleep(1000);
this.label1.Text = System.DateTime.Now.ToString();
}
}
}
}

 

 

转载于:https://www.cnblogs.com/shineqiujuan/archive/2008/10/16/1312788.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值