主题订单执行?订单、主题

2023-09-03 17:48:23 作者:喵喵╭╮

我有这个简单的code:(我运行linqpad 的)

I have this simple code : (which i run in linqpad)

void Main()
{
    for ( int  i=0;i<10;i++)
     {
      int  tmp=i;
      new Thread (() =>doWork(tmp)).Start();
     }
}

 public void doWork( int h)
 {
 h.Dump();
 }

INT TMP =我; 行是捕捉变量 - 所以每次迭代都会有其存在的价值。

the int tmp=i; line is for capture variable - so each iteration will have its own value.

2的问题:

1)的数字的没有的顺序,而线程执行的!

1) the numbers are not sequential , while thread execution is !

2)有时我得到的少的超过10个号码!

2) sometimes i get less than 10 numbers !

下面是一些执行输出:

问题

1)为什么1的情况下发生了,我该如何解决呢?

1) why case 1 is happening and how can i solve it ?

2)为什么情况2发生,我该如何解决呢?

2) why case 2 is happening and how can i solve it ?

推荐答案

不应该期望他们是连续的。每个线程的优先级作为内核选择。它可能发生,他们看起来连续的,纯粹是当每个启动的性质,但是这是纯粹的机会。

It should not be expected that they are sequential. Each thread gets priority as the kernel chooses. It might happen that they look sequential, purely by the nature of when each is started, but that is pure chance.

有关确保他们都完成 - 纪念每一个新的线程为的IsBackground = FALSE ,使之保持可执行活着。例如:

For ensuring that they all complete - mark each new thread as IsBackground = false, so that it keeps the executable alive. For example:

new Thread(() => doWork(tmp)) { IsBackground = false }.Start();