目的:確認Thread.Sleep(500)的影響范圍
構想:使用3個progressBar&3個線程,分別在線程內執行Thread.Sleep(500)&Thread.Sleep(1000)&Thread.Sleep(2000),查看progressBar狀態,反映出時間sleep的狀況
結果:雖然很傻,不過最終還是確認到現象,thread.sleep的影響范圍是執行thread.sleep的所在線程(雖然此前在优快云的論壇中已經獲得答案,不過證實一下心里踏實)
源碼:
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 TEST
{
public delegate void _Delegate_T();
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
_Delegate_T _DT_T1 = null;
_Delegate_T _DT_T2 = null;
_Delegate_T _DT_T3 = null;
Thread T1 = null;
Thread T2 = null;
Thread T3 = null;
private void button1_Click(object sender, EventArgs e)
{
T1 = new Thread(p1);
T2 = new Thread(p2);
T3 = new Thread(p3);
_DT_T1 = new _Delegate_T(_DT_T_M1);
_DT_T2= new _Delegate_T(_DT_T_M2);
_DT_T3 = new _Delegate_T(_DT_T_M3);
T1.IsBackground = true;
T1.Start();
T2.IsBackground = true;
T2.Start();
T3.IsBackground = true;
T3.Start();
}
public void _DT_T_M1()
{
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(_DT_T1);
}
else
{
progressBar1.Increment(1);
if (progressBar1.Value == progressBar1.Maximum)
progressBar1.Value = 0;
}
}
public void _DT_T_M2()
{
if (progressBar2.InvokeRequired)
{
progressBar2.Invoke(_DT_T2);
}
else
{
progressBar2.Increment(1);
if (progressBar2.Value == progressBar2.Maximum)
progressBar2.Value = 0;
}
}
public void _DT_T_M3()
{
if (progressBar3.InvokeRequired)
{
progressBar3.Invoke(_DT_T3);
}
else
{
progressBar3.Increment(1);
if (progressBar3.Value == progressBar3.Maximum)
progressBar3.Value = 0;
}
}
public void p1()
{
while (this.T1.IsAlive)
{
Thread.Sleep(500);
_DT_T1();
}
}
public void p2()
{
while (this.T2.IsAlive)
{
Thread.Sleep(1000);
_DT_T2();
}
}
public void p3()
{
while (this.T3.IsAlive)
{
Thread.Sleep(2000);
_DT_T3();
}
}
}
}