gpt4 book ai didi

c# - 对于 WinRT Metro Apps 什么等同于 Parallel.ForEach

转载 作者:行者123 更新时间:2023-11-30 22:27:57 25 4
gpt4 key购买 nike

这是有关 Parallel.For 的 MSDN 页面中的示例代码。我想在 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);
}

关于c# - 对于 WinRT Metro Apps 什么等同于 Parallel.ForEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11053997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com