110,538
社区成员
发帖
与我相关
我的任务
分享
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 csdnWinform
{
public partial class Form1 : Form
{
private int _sleepCount = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//非UI线程执行耗时操作(这里是更新UI上的Label 显示当前精确时间)
var timeThread = new Thread(() =>
{
while (true)
{
//休眠1秒 模拟操作 这里相当于秒表
Thread.Sleep(1000);
//这里是外部定义的线程休眠时间 默认情况下_sleepCount为0 所以会忽略这个停顿
Thread.Sleep(this._sleepCount);
//重置线程休眠时间
this._sleepCount = 0;
if (label1.InvokeRequired)
{
this.Invoke(new Action(() => this.label1.Text = DateTime.Now.ToString()));
}
else
{
this.label1.Text = DateTime.Now.ToString();
}
}
});
timeThread.IsBackground = true;
timeThread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
int sleepCount = 0;
if (!int.TryParse(textBox1.Text,out sleepCount))
{
MessageBox.Show("Sleep Count Illeadge");
return;
}
//修改全局_sleepCount变量 这样在任务线程里面也就会有指定时间的休眠
_sleepCount = sleepCount * 1000;
}
}
}
新的一个线程。
Thread th = new Thread(new ParameterizedThreadStart(start));
th.Start();
在线程方法里面悬停线程。
private static void start(object _obj)
{
Thread.Sleep(1000);
}