本篇讲一下如何编写线程安全的Winform 程序
有问题的代码#
一个很简单的功能,Winform上实时显示当前时间:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public partial class Form1 : Form
{
private System.Threading.Timer _timer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_timer = new System.Threading.Timer(UpdateTime, null, 0, 20);
}
private void UpdateTime(object state)
{
lblTime.Text = DateTime.Now.ToString("hh:mm:ss");
}
}
|
F5 运行,出错了: