多线程应用最多的场景是处理比较大的或耗时的任务,如数据采集、网络扫描、返回实时进度条信息等。下面的示例展示了两个线程同时工作,代码如下:
protected void Button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(method2));
th.Start();
for (int i = 0; i < 10; i++)
{
Label1.Text += i.ToString();
Thread.Sleep(100);
}
}
private void method2()
{
string[] strList = new string[] { "a","b","c","d","e","f","g","h","i","j"};
for (int i = 0; i < 10; i++)
{
Label1.Text += strList[i];
Thread.Sleep(100);
}
}