You could use events to sync. Like this:
private static ManualResetEvent resetEvent = new ManualResetEvent(false);
public static void Main()
{
ThreadPool.QueueUserWorkItem(arg => DoWork());
resetEvent.WaitOne();
}
public static void DoWork()
{
Thread.Sleep(5000);
resetEvent.Set();
}
If you don't want to embed event set into your method, you could do something like this:
var resetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
arg =>
{
DoWork();
resetEvent.Set();
});
resetEvent.WaitOne();
For multiple items:
var events = new List<ManualResetEvent>();
foreach(var job in jobs)
{
var resetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
arg =>
{
DoWork(job);
resetEvent.Set();
});
events.Add(resetEvent);
}
WaitHandle.WaitAll(events.ToArray());