使用任务工厂存储每个任务的任务完成时间



我正在使用任务工厂来生成并行线程,我的代码如下。我需要打印每个线程的完成时间,但不知道如何检查每个线程。目前,我的代码正在等待所有任务完成,然后计算时间。

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();

您可以向Task添加延续。延续是一种在给定Task完成时将调用的方法。

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                
    });
}

如果您需要为单个任务计时,则每个任务需要一个秒表。您可以在StartNew内启动StopWatch,然后在ContinueWith中停止它。

如果这是您的实际代码,您可以简单地对调用的同步操作进行计时 (http.在这种情况下为同步请求)。例如,以下代码就足够了。

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);
}

顺便说一句,网络操作本质上是异步的;将有异步 API 可用,您可以使用它而不是在任务中包装同步 Web 请求。例如,也许HttpClient.SendAsync.

我首先要说的是,您不需要线程池线程来执行异步 IO 绑定操作。与其使用Task.Factory.StartNew,不如使用自然异步的API,例如HttpClient提供的API。

然后,我想说您可以使用Task.WhenAny来等待每个任务完成

// 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);
}

最新更新