Saving task completion time for each task using Task factory

I am using the factory task to create parallel threads, and my code is as follows. I have a requirement to print the completion time of each thread, but I do not know how to check each thread. Currently, my code is waiting for the completion of all tasks, and then the calculation of time.

stp1.Start(); for (int i = 0; i < tsk.Length; i++) { tsk[i] = Task.Factory.StartNew((object obj) => { resp = http.SynchronousRequest(web, 443, true, req); }, i); } try { Task.WaitAll(tsk); } stp1.Stop(); 
+7
multithreading c #
source share
2 answers

You can add a sequel to Task . Continuation is a method that will be called when the specified Task completed.

 for (int i = 0; i < tsk.Length; i++) { tsk[i] = Task.Factory.StartNew((object obj) => { resp = http.SynchronousRequest(web, 443, true, req); }, i); tsk[i].ContinueWith(antecedent=> { //antecedent is completed //Do whatever here }); } 

If you need to complete individual tasks, you will need one stopwatch for each task. You can start StopWatch inside StartNew and stop it in ContinueWith .

If this is your actual code, you can simply time the synchronous operation that you are calling (http.SynchronousRequest in this case). For example, the following code is enough.

 for (int i = 0; i < tsk.Length; i++) { tsk[i] = Task.Factory.StartNew((object obj) => { StopWatch watch = StopWatch.StartNew(); resp = http.SynchronousRequest(web, 443, true, req); watch.Stop(); Console.WriteLine(watch.Elapsed); }, i); } 

Btw, network operations are inherently asynchronous; An asynchronous API will be available, you can use it instead of wrapping a synchronous web request in Task. For example, perhaps HttpClient.SendAsync .

+7
source share

I would say that you do not need threadpool threads to perform async IO operations. Instead of using Task.Factory.StartNew use, of course, an asynchronous API, for example, one HttpClient .

Then, I would say you can use Task.WhenAny to wait for the completion of each of your tasks upon completion:

 // Note I'm assuming some kind of async implementation which returns a Task<T> var tasks = tsk.Select(req => http.AsyncRequest(web, 443, true, req)); while (tasks.Count > 0) { var finishedTask = await Task.WhenAny(tasks); // Do something with finishedTask tasks.Remove(finishedTask); } 
+1
source share

All Articles