2012-06-15 35 views
2

這是MSDN頁面中關於Parallel.For的示例代碼。我想在WinRT C#中做同樣的事情:WinRT Metro Apps相當於Parallel.ForEach

#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

此時沒有一個等效的方法。包含'Parallel.ForEach'的.NET Framework擴展目前不包含在Win RT .NET Profile中。如果是,那麼你的代碼就可以工作。 **隨意寫一個自己。** –

回答

3

Metro應用程序不應該執行繁重的CPU密集型操作。我不確定應用商店的要求是什麼,但如果您的應用在最長時間超出CPU時被拒絕,我不會感到驚訝。

也就是說,地鐵確實有並行異步操作的支持,你可以用這個做一些基本的並行處理(如果你必須):

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); 
} 
+0

謝謝斯蒂芬,多數民衆贊成我正在尋找。 –

相關問題