2009年12月27日 星期日

[c#] 單一執行緒與委派 應用介紹-[Thread and Delegate]

單一執行緒與委派 應用介紹-[Thread and Delegate]

//產生紅色球球
bool flg1, flg2,flg3;

private void button1_Click(object sender, EventArgs e)
{

flg1 = true;
Thread th1 = new Thread(readtst);
th1.Start();

}

//執行緒目標
public void readtst()
{
while (flg1 == true)
{
textBox1.BeginInvoke(new creatball(rdball ));
Thread.Sleep(10);
}
}

//委派目標 (執行緒委派目標值傳回到form的物件)
private delegate void creatball( );
private void tst()
{
textBox1.AppendText("read ball" +DateTime .Now .ToLongTimeString ()+ "\n");
}

//委派目標 - 產生紅色球球
public void rdball()
{
Ball aBall;
aBall.pt = new Point(rd.Next(20, this.ClientSize.Width - 20), rd.Next(40, this.ClientSize.Height - 20));
aBall.color = Color.Red;

lock (this)
{
ballList.Add(aBall);
textBox1.AppendText("Read"+DateTime .Now .ToLongTimeString ()+ "\n");
}

this.Invalidate();
}

沒有留言:

張貼留言