2012-04-17 116 views
1

我非常缺乏经验的利用多线程技术,但这里是我曾尝试:C#生成新线程,然后等待

Thread thread = null; 

for (int minute = 0; minute < 60; minute++) 
{ 
    Thread.Sleep(60000); 

    if (thread != null) 
    { 
     while (thread.ThreadState == ThreadState.Running) { } 
    } 

    thread = new Thread(delegate() 
    { 
     // Do stuff during the next minute whilst the main thread is sleeping. 
    }); 
    thread.Start(); 
} 

我想在这里实现的是有一个线程在运行,做在主线程休眠时工作,但我不确定为什么上面的代码不起作用。会发生什么是在第一个循环之后(在启动线程之后),ThreadState似乎没有从“Running”中改变。我也很好奇这是否有更优雅的方式。

有人知道这个问题吗?

+0

感谢所有的答案,但也许不清楚我想达到什么。我想运行线程委托中给出的代码,而主线程睡眠一分钟,但如果新线程在这一分钟内没有完成,那么主线程将在创建另一个新线程之前等待它完成。这是必需的,以便分钟数尽可能接近真实分钟。 – TheBoss 2012-04-17 05:23:17

+0

嗯..仍然没有得到它。你说的是主线程应该等到产生的线程结束,但至少要一分钟?是对的吗? – harri 2012-04-17 05:52:33

+0

下面是过程应该如何进行的:在for循环的第一次迭代中,主线程将等待1分钟,之后它将创建一个新线程来并行执行任务。开始这个新线程后,它会再次迭代,主线程休眠1分钟,然后如果并行任务[奇怪]在那一分钟内没有完成任务,它将等待它完成。一旦并行任务完成后,它将创建一个新的线程等。 – TheBoss 2012-04-17 12:30:52

回答

4

Thread.Join是等待线程结束的更好方法。

+0

我的代码中实际存在一个问题,导致并行代码无限期地运行。我实施了这个,谢谢。 – TheBoss 2012-04-17 12:54:03

0

Thread.Sleep(60000)在调用它的线程上执行,在这种情况下是主线程。这很好,但“线程”不知道它已经运行了多长时间,也不知道何时停止。你需要有一个对象告诉“线程”它已经运行了60秒。

Thread thread = null; 

for (int minute = 0; minute < 60; minute++) 
{ 
    if (thread != null) 
    { 
     while (thread.ThreadState == ThreadState.Running) { } 
    } 

    thread = new Thread(delegate() 
    { 
     try 
     { 
      // Do stuff during the next minute whilst the main thread is sleeping. 
     } 
     catch (ThreadAbortException ex) 
     { 
     } 
    }); 
    thread.Start(); 
    Thread.Sleep(60000); 
    thread.Abort(); 
} 

这应该达到你想要的,但并不是真正停止线程的最优雅方式。一个线程应该使用回调来结束。

2

如果您使用的是.Net 4,我建议您查看Task Class。它使多线程的工作更容易/直接。

0

你可能会寻找更多的东西是这样的:

Thread thread = new Thread(delegate() 
    { 
     // Something that takes up to an hour 
    }); 
thread.Start(); 

for (int minute = 0; minute < 60; minute++) 
{ 
    Thread.Sleep(60000); 
    if (thread.IsAlive) 
     Console.WriteLine("Still going after {0} minute(s).", minute); 
    else 
     break; // Finished early! 
} 

// Check if it's still running 
if (thread.IsAlive) 
{ 
    Console.WriteLine("Didn't finish after an hour, something may have screwed up!"); 
    thread.Abort(); 
} 

如果这是你在找什么,我想看看在BackgroundWorker类。

1

使用Task类可以做到这一点。

Task task = Task.Factory.StartNew(() => 
    { 
    // Do stuff here. 
    }); 

task.Wait();