1
爲什麼我得到以下文的代碼段不同的結果ThreadLocal的聚合和任務並行庫
代碼示例1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadLocalTasks
{
class Program
{
static void Main(string[] args)
{
ThreadLocal<int> aggregrations = new ThreadLocal<int>();
Task<int>[] tasks = new Task<int>[10];
for (int i = 0; i < tasks.Length; i++)
{
aggregrations.Value = 0;
int tempi = i;
tasks[tempi] = new Task<int>(() =>
{
int temp = 0;
for (int j = 1; j <= 3; j++)
{
temp += j;
}
aggregrations.Value = temp;
return aggregrations.Value;
});
}
tasks.ToList().ForEach(x => {
x.Start();
});
Task.WaitAll(tasks);
int sum = 0;
tasks.ToList().ForEach(x =>
{
sum += x.Result;
});
Console.WriteLine("Sum: {0}", sum);
Console.WriteLine("Press any key to quit..");
Console.ReadKey();
}
}
}
樣品2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadLocalTasks
{
class Program
{
static void Main(string[] args)
{
ThreadLocal<int> aggregrations = new ThreadLocal<int>();
Task<int>[] tasks = new Task<int>[10];
for (int i = 0; i < tasks.Length; i++)
{
aggregrations.Value = 0;
int tempi = i;
tasks[tempi] = new Task<int>(() =>
{
for (int j = 1; j <= 3; j++)
{
aggregrations.Value += j;
}
return aggregrations.Value;
});
}
tasks.ToList().ForEach(x => {
x.Start();
});
Task.WaitAll(tasks);
int sum = 0;
tasks.ToList().ForEach(x =>
{
sum += x.Result;
});
Console.WriteLine("Sum: {0}", sum);
Console.WriteLine("Press any key to quit..");
Console.ReadKey();
}
}
}
這是不是這麼多,爲什麼你會做到這一點,更多的是這個技術是正確的。 – Blair 2010-11-28 01:28:20
我添加了一個更詳細的解釋,爲什麼你的兩個例子都是'不正確的'。 – 2010-12-01 01:12:12