这是来自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#是什么?

我应该创建一个任务数组并等待该数组完成吗?

最佳答案

Metro应用程序不应执行大量的CPU密集型操作。我不确定应用商店的要求是什么,但是如果您的应用在相当长的时间内使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);
}

09-09 21:40
查看更多