今天心血來潮,寫一個multi-thread的程式
有助於未來可以解決很多問題
public partial class Form1 : Form
{
private AutoResetEvent[] m_ThreadExited;
private BackgroundWorker[] m_Thread;
private bool[] m_isthread ;
bool m_show = false;
int camcount = 4;
public Form1()
{
InitializeComponent();
m_Thread = new BackgroundWorker[camcount];
m_ThreadExited = new AutoResetEvent[camcount];
m_isthread = new bool[camcount];
for (int i = 0; i < camcount; i++)
{
m_ThreadExited[i] = new AutoResetEvent(false);
m_isthread[i] = false;
}
}
private void main()
{
if (m_show == false)
{
m_show = true;
for (int i = 0; i < camcount; i++)
CreateThread(i);
}
else
{
m_show = false;
for (int i = 0; i < camcount; i++)
m_isthread[i] = false;
}
}
private void CreateThread(int i)
{
m_isthread[i] = true;
m_Thread[i] = new BackgroundWorker();
m_Thread[i].ProgressChanged += new ProgressChangedEventHandler(UpdateLoopUI);
m_Thread[i].DoWork += new DoWorkEventHandler(Loop);
m_Thread[i].WorkerReportsProgress = true;
m_Thread[i].RunWorkerAsync(i); // RunWorkerAsync(i) ,其中的i救世會傳送到LOOP ,用e.Arugment去讀取數值,i也可以改成字串
}
private void UpdateLoopUI(object sender, ProgressChangedEventArgs e)
{
int i = e.ProgressPercentage;//讀進度的方法
int test = (int)e.UserState;//讀取參數值
richTextBox1.AppendText( test.ToString()+"\n");
}
private void Loop(object sender, DoWorkEventArgs e)
{
int i = (int)e.Argument;//這是剛讀進來的值,如果是字串則用string
BackgroundWorker worker = sender as BackgroundWorker;
while (m_isthread[i])
{
worker.ReportProgress(i,i);//the second i is userstate 傳輸值
System.Threading.Thread.Sleep(100);
}
m_ThreadExited[i].Set();
}
}
留言列表