I have a C # console application that has some threads to do some work (file upload). each thread can exit the application at any time anywhere in the application, but I will show the corresponding message on the console. You can track them, but that doesn't make sense to me. I want to just check the number of threads or something like that, to find out which one is the last, and to do something when it exits. What is the best practice for this?
pseudo code:
if (lastThread) { cleanUp(); Console.ReadLine(); }
thank
, . , , :
var task1 = Task.Factory.StartNew( () => DoTaskOneWork() ); var task2 = Task.Factory.StartNew( () => DoTaskTwoWork() ); var task3 = Task.Factory.StartNew( () => DoTaskThreeWork() ); // Block until all tasks are done Task.WaitAll(new[] {task1, task2, task3} ); cleanUp(); // Do your cleanup
"" , PLINQ:
var fileUrls = GetListOfUrlsToDownload(); fileUrls.AsParallel().ForAll( fileUrl => DownloadAndProcessFile(fileUrl) ); cleanUp(); // Do your cleanup
, , .
, , , , , WaitAll .
, , . , , , . , , , , , WaitAll . , - try...finally, .
WaitAll
try...finally
foreach (workitem in list of work) start up thread associated with a ManualResetEvent or similar WaitAll for all events to be signalled cleanup
join . , , .
WaitHandle, ManualResetEvent , .