我是C#中并行编程的新手,我发现很难实时实现。这是我的疑问:
public string[] SequentialFun(int count)
{
string[] results = new string[count];
for(int run = 0; run < count; run++)
{
while(true)
{
//Generate a Random Number (62 bit) and store it in variable 'randNum'
if(randNum is prime)
{
results[run] = randNum.ToString();
break;
}
}
}
return results;
}
Parallel.For
循环直到某个条件?
请解释并帮助我详细解释。答案 0 :(得分:0)
只需更换顺序循环:
for (int run = 0; run < count; run++)
{
// ...
}
......并行:
Parallel.For(0, count, run =>
{
// ...
});
答案 1 :(得分:0)
您应该使用Parallel.For
方法并将您的逻辑放在匿名委托中:
Parallel.For(0, count, (i, results) =>
{
while(true)
{
//Generate a Random Number (62 bit) and store it in variable 'randNum'
if(randNum is prime)
{
results[run] = randNum.ToString();
break;
}
}
}
);
请记住,使用Parallel.For
并不意味着代码执行的效率会提高x倍,因为它取决于处理器核心的数量。