I\'m writing a C# console app and having an issue where the primary thread closes before all the spawned off Tasks have a chance to complete. General program flow looks like thi
You can put all of the tasks you get into a List
instead of just creating them and tossing them, and then use the Task.WaitAll()
to wait for completion:
var tasks = new List();
foreach (KeyValuePair> entry in productDictionary) {
string writePath = String.Format(@"{0}\{1}-{2}.txt", directoryPath, hour, entry.Key);
List quotes = entry.Value;
// add task to list
tasks.Add(Task.Factory.StartNew(() => WriteProductFile(writePath, quotes)));
}
// now wait for all tasks to finish, you'd also want to handle exceptions of course.
Task.WaitAll(tasks.ToArray());
There are many variations of WaitAll()
, you could wait indefinitely (as above), or wait for a TimeSpan
and if time-out then print a progress message and wait again, etc...