编辑:
哎呀,我也第一次感到困惑。
问题是它看起来只是累加的(累积的),因为 ElapsedTime 值始终仅按递增顺序输出。
所以,如果我有,如下面的演示,按启动顺序:
- 第一次启动任务的持续时间为 10 秒(10000 毫秒),
- 第二个任务的持续时间为 8 秒(8 000 毫秒),
- 3d 任务的持续时间为 6 秒(6 000 毫秒),
然后结果以初始顺序出现在输出中 - 总是按任务持续时间增加的顺序:
- 第一个输出:3d 启动任务的持续时间(6 秒持续时间)
- 第二个输出:第二个启动任务的持续时间(持续时间为 8 秒)
- 输出中的 3d(最后一个):第一个启动任务的持续时间(10 秒持续时间)
以下是控制台应用程序的输出:
from DoSomething 6043
from main 6043
from DoSomething 8057
from main 8057
from DoSomething 10058
from main 10058
原因很明显 - 因为更快的任务总是在更长(更耗时)的任务之前完成并输出。
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var iResult = new List<Task>();
for (int i=5; i>2; i--)
{
int load = i;
var task = Task.Factory.StartNew(() =>
DoSomething(load), TaskCreationOptions.LongRunning);
//following commented lines do NOT change the behavior in question
task.ContinueWith(m => Console.WriteLine("from main "+m.Result));
//iResult.Add(task);
}
Console.ReadLine();
}
//public static myMsg DoSomething()
public static long DoSomething(int load)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
//usage of either prev or following 2 lines produce the same results
//Stopwatch timer = new Stopwatch(); //instead of prev .StartNew();
//timer.Start();// instead of prev .StartNew();
Console.WriteLine("***Before calling DoLongRunningTask() "
+ timer.ElapsedMilliseconds);
Console.WriteLine("GetHashCode "+timer.GetHashCode());
DoLongRunningTask(load);
timer.Stop();
long elapsed = timer.ElapsedMilliseconds;
Console.WriteLine("from DoSomething "+ elapsed);
return elapsed;//return new myMsg(timer.ElaspedMilliseconds);
}
public static void DoLongRunningTask(int load)
{
Thread.Sleep(2000*load);
/******************* another variant of calculation intensive loading
load = load;
double result = 0;
for (int i = 1; i < load*100000; i++)
result += Math.Exp(Math.Log(i) );
*/
}
}
}