【发布时间】:2019-06-10 15:37:43
【问题描述】:
我的部分研究项目是使用秒表来测量时间。
每个秒表用于不同的任务,以测量 while 循环应该工作多长时间。
我想知道如果我放了很多长任务,这个措施会不会 准确。
创意代码示例:
public static void run(){
var tasks= new List<Task<int>>();
foreach(var task in taskList) //taskList is global object with 10 variables inside
tasks.Add(Task.Factory.StartNew<int>(()=>taskFunction(task)));
Task.WaitAll(tasks.ToArray());
}
private int taskFunction(task) {
Stopwatch watch = new Stopwatch();
while (watch.ElapsedMilliseconds < MaxTime * 1000)
{
watch.Start();
doSomething(); // takes lot of time;
watch.Stop();
doSomethingDiffrent();
}
}
所以我将创建大约 10 个任务。如果任务不是由处理器计算,是否会在秒表中运行并浪费时间?
【问题讨论】:
-
是的,它应该可以正确运行和测量。如果在任务之外声明了 thr StopWatch,您可能会遇到线程问题,因为它不是线程安全的。
-
好的,谢谢。我不知道为什么人们会减去这个问题..
标签: c# .net visual-studio task stopwatch