2

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

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

4

1 回答 1

3

Metro apps aren't supposed to do heavy CPU-intensive operations. I'm not sure what the app store requirements are, but I wouldn't be surprised if your app is rejected if it maxes out the CPU for a significant amount of time.

That said, Metro does have support for parallel asynchronous operations, and you can use this to do some basic parallel processing (if you must):

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);
}
于 2012-06-16T13:55:42.810 回答