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();
}

[c#] 由函式反向傳遞直給飲用者 應用介紹-[public void mystr(out string x)]

由函式反向傳遞值給引用者 應用介紹-[public void mystr(out string x)]

//函式引用者取值
private void button1_Click(object sender, EventArgs e)
{
string x;
mystr(out x);
textBox1.Text = x;
}

//反向送出函式
public void mystr(out string x)
{
x = "read";
Console.WriteLine(x);
}

2009年12月26日 星期六

[c#] delegate and winform object 應用介紹-[delegate]

delegate and winform object 應用介紹-[delegate]

//如何使用delegate把對象傳回到windows form

//傳回到windows form 物件
private void button1_Click(object sender, EventArgs e)
{
textBox1.BeginInvoke(new creatball(tst));
}

//委派對象
public delegate void creatball();
public void tst()
{
textBox1.AppendText("aaaa");
}