我是TPL的新手,所以只是通过一些关于相同的教程, http://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx
在上面链接我正在尝试使用此代码
var displayData = Task.Factory.StartNew(() => {
Random rnd = new Random();
int[] values = new int[100];
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
values[ctr] = rnd.Next();
return values;
} ).
ContinueWith((x) => {
int n = x.Result.Length;
long sum = 0;
double mean;
for (int ctr = 0; ctr <= x.Result.GetUpperBound(0); ctr++)
sum += x.Result[ctr];
mean = sum / (double) n;
return Tuple.Create(n, sum, mean);
} ).
ContinueWith((x) => {
return String.Format("N={0:N0}, Total = {1:N0}, Mean = {2:N2}",
x.Result.Item1, x.Result.Item2,
x.Result.Item3);
} );
var displayData = Task.Factory.StartNew(() => {
Random rnd = new Random();
int[] values = new int[100];
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
values[ctr] = rnd.Next();
return values;
} ).
ContinueWith((x) => {
int n = x.Result.Length;
long sum = 0;
double mean;
for (int ctr = 0; ctr <= x.Result.GetUpperBound(0); ctr++)
sum += x.Result[ctr];
mean = sum / (double) n;
return Tuple.Create(n, sum, mean);
} ).
ContinueWith((x) => {
return String.Format("N={0:N0}, Total = {1:N0}, Mean = {2:N2}",
x.Result.Item1, x.Result.Item2,
x.Result.Item3);
} );
我正在使用我的代码替换上面的代码
var taskList = Task.Factory.StartNew(() => {
var newRandom = new Random();
var intArray = new int[100];
Console.WriteLine("Begining of First Iteration");
Parallel.For(0, intArray.GetUpperBound(0) - 1, i =>
{
intArray[i] = newRandom.Next();
Console.WriteLine(i);
});
Console.WriteLine("End of First Iteration");
}).ContinueWith((x) => {
Console.WriteLine("Beginning of Second Iteration");
int n = x.Result.Length;
long sum = 0;
double mean;
for (int ctr = 0; ctr <= x.Result.GetUpperBound(0); ctr++)
sum += x.Result[ctr];
mean = sum / (double)n;
Console.WriteLine("End of Second Iteration");
return Tuple.Create(n, sum, mean);
});
我收到错误::
var taskList = Task.Factory.StartNew(() => {
var newRandom = new Random();
var intArray = new int[100];
Console.WriteLine("Begining of First Iteration");
Parallel.For(0, intArray.GetUpperBound(0) - 1, i =>
{
intArray[i] = newRandom.Next();
Console.WriteLine(i);
});
Console.WriteLine("End of First Iteration");
}).ContinueWith((x) => {
Console.WriteLine("Beginning of Second Iteration");
int n = x.Result.Length;
long sum = 0;
double mean;
for (int ctr = 0; ctr <= x.Result.GetUpperBound(0); ctr++)
sum += x.Result[ctr];
mean = sum / (double)n;
Console.WriteLine("End of Second Iteration");
return Tuple.Create(n, sum, mean);
});
找不到&#34;结果&#34;
我做错了什么?
答案 0 :(得分:4)
Task
类没有Result
属性,Task<T>
属性。
问题是,StartNew
中的代理人没有返回值,因此它解析为返回Task
而不是Task<T>
。
尝试添加此内容:
...
Console.WriteLine("End of First Iteration");
return intArray;