dow*_*one 6 c# multithreading .net-4.0 console-application
可能重复:
C#:等待所有线程完成
我有一个控制台应用程序产生一些线程,然后退出.每个线程大约需要20秒才能完成.似乎控制台应用程序正在生成线程,然后在线程有机会完成之前退出.
如何告诉控制台应用程序在它生成的所有线程完成之前不要退出?
是否为循环生成了线程?如果是这样,Parallel.ForEach将起作用:
ParallelOptions options = new ParallelOptions();
Parallel.ForEach(items, options, item=>
{
// Do Work here
}
});
Run Code Online (Sandbox Code Playgroud)
你可以用一个CountDownEvent.
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static CountdownEvent countdown;
static void Main(string[] args)
{
countdown = new CountdownEvent(1);
for (int i = 1; i < 5; i++)
{
countdown.AddCount(); //add a count for each (BEFORE starting thread .. Thanks, Brian!)
//do stuff to start background thread
}
countdown.Signal(); //subtract your initial count
countdown.Wait(); //wait until countdown reaches zero
//done!
}
static void backgroundwork()
{
//work
countdown.Signal(); //signal this thread's completion (subtract one from count)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5149 次 |
| 最近记录: |