主线程执行委托Demo:
1..无委托执行线程
private void button1_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(mtd));
th1.Start();
}
private void mtd()
{
Thread.Sleep(3000);
MessageBox.Show("线程启动了");
}
2.//用主线程执行委托
private void button1_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(mtd));
th1.Start();
}
private delegate void mydel();
private void mtd()
{
Thread.Sleep(3000);
MessageBox.Show("线程启动了,接下来要执行委托方法了。。。");
mydel d = new mydel(fun); //用主线程执行委托
d += fun;
d();
}
private void fun()
{
Thread.Sleep(2000);
MessageBox.Show("我是被委托执行的");
}
3.//用主线程执行委托
private void button1_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(mtd));
th1.Start();
}
private delegate void mydel();
private void mtd()
{
Thread.Sleep(3000);
MessageBox.Show("线程启动了,接下来要执行委托方法了。。。");
mydel d = new mydel(fun);
this.Invoke(d,null);//调用执行委托方法
}
private void fun()
{
Thread.Sleep(2000);
MessageBox.Show("我是被委托执行的");
}
4.线程Demo
private void button1_Click(object sender, EventArgs e)
{
//创建一个线程组,同时开启多个线程,分别委托执行某一个方法
ThreadStart ths = new ThreadStart(this.fun);
Thread[]th = new Thread[3];
for (int i = 0; i < 3;i++ )
{
th[i] = new Thread(ths);
th[i].Start();
}
}
int adsum = 0;
private void fun()
{
lock (this) //若不锁,则出现抢进程情况
{
for (int i = 0; i < 3; i++)
{
adsum += 2;
MessageBox.Show(adsum.ToString());
}
}
}
5.
private void button1_Click(object sender, EventArgs e)
{
ThreadStart thst = new ThreadStart(add);
Thread th = new Thread(thst);
th.Start();
Thread th1 = new Thread(thst);
th1.Start();
Thread th2 = new Thread(thst);
th2.Start();
}
int k;
private void add()
{
lock(this)
{
for (int i = 0; i < 100; i++)
{
k++;
}
MessageBox.Show(k.ToString());
}
}