110,571
社区成员
发帖
与我相关
我的任务
分享
for (int i = 0; i < 100; i++)
{
this.rtb_test.AppendText("for "+i.ToString()+"\n");
int temp = i;
Thread th = new Thread(new ParameterizedThreadStart(method));
th.Start(temp);
}
private void method(object obj)
{
this.rtb_test.AppendText(obj.ToString()+" thread xxxxx !!!!"+"\n");
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(method);
t.Start(0);
Thread.Sleep(3000);//延时3秒
}
public void method(object obj)
{
BeginInvoke(new Action(() => {
Debug.WriteLine("thread {0}:委托开始{1}", obj, Environment.NewLine);
rtb_test.AppendText(String.Format("thread {0}:委托开始{1}", obj, Environment.NewLine));
}));
Debug.WriteLine("thread {0}:线程结束{1}", obj, Environment.NewLine);
}
看到了吧,线程都结束了,主线程空闲了才执行委托。
所以给了你参考代码:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() => {
for (int i = 0; i < 100; i++)
{
Invoke(new Action(() => {
rtb_test.AppendText(String.Format("for {0}{1}", i, Environment.NewLine));
}));
Thread th = new Thread(method);
th.Start(i);
}
});
thread.Start();
rtb_test.AppendText(
"委托工作都放在队列,主线程有空闲就能处理!\n" +
"这句话说完了,空闲了就可以处理委托工作了!\n"
);
}
public void method(object obj)
{
BeginInvoke(new Action(() => {
rtb_test.AppendText(String.Format("thread {0}:委托开始{1}", obj, Environment.NewLine));
}));
}
private static void method(object obj)
{
Console.WriteLine(obj.ToString() + " thread xxxxx !!!!" + "\n");
}
for (int i = 0; i < 100; i++)
{
Console.WriteLine("for " + i.ToString() + "\n");
int temp = i;
Task.Run(() => {
method(temp);
});
}