这是MSDN页面中关于Parallel.For的示例代码。我想在WinRT C#中做同样的事情:
#region Sequential_Loop
static void MultiplyMatricesSequential(double[,] matA, double[,] matB, double[,] result)
{
int matACols = matA.GetLength(1);
int matBCols = matB.GetLength(1);
int matARows = matA.GetLength(0);
for (int i = 0; i < matARows; i++)
{
for (int j = 0; j < matBCols; j++)
{
for (int k = 0; k < matACols; k++)
{
result[i, j] += matA[i, k] * matB[k, j];
}
}
}
}
#endregion
#region Parallel_Loop
static void MultiplyMatricesParallel(double[,] matA, double[,] matB, double[,] result)
{
int matACols = matA.GetLength(1);
int matBCols = matB.GetLength(1);
int matARows = matA.GetLength(0);
// A basic matrix multiplication.
// Parallelize the outer loop to partition the source array by rows.
Parallel.For(0, matARows, i =>
{
for (int j = 0; j < matBCols; j++)
{
// Use a temporary to improve parallel performance.
double temp = 0;
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
result[i, j] = temp;
}
}); // Parallel.For
}
#endregion
WinRT Metro的等效int C#是什么?
我应该创建一个任务数组并等待数组完成吗?
答案 0 :(得分:3)
Metro应用程序不应该执行繁重的CPU密集型操作。我不确定应用程序商店的要求是什么,但如果你的应用程序在很长一段时间内最大限度地耗尽你的应用程序,我也不会感到惊讶。
也就是说,Metro确实支持并行异步操作,您可以使用它来进行一些基本的并行处理(如果必须的话):
static async Task MultiplyMatricesAsync(double[,] matA, double[,] matB, double[,] result)
{
int matACols = matA.GetLength(1);
int matBCols = matB.GetLength(1);
int matARows = matA.GetLength(0);
var tasks = Enumerable.Range(0, matARows).Select(i =>
Task.Run(() =>
{
for (int j = 0; j < matBCols; j++)
{
// Use a temporary to improve parallel performance.
double temp = 0;
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
result[i, j] = temp;
}
}));
await Task.WhenAll(tasks);
}