gpt4 book ai didi

c# - Parallel.For 属性

转载 作者:行者123 更新时间:2023-11-30 17:57:54 26 4
gpt4 key购买 nike

public static void Main (string[] args)
{
int k = 0;
int i = 3;
var loopRes = Parallel.For (0, 20, (J) =>
{
k = i / J;
Console.WriteLine ("Result After division " + J + " = " + k);
}
);

if (loopRes.IsCompleted) {
Console.WriteLine ("Loop was successful");
}
if (loopRes.LowestBreakIteration.HasValue) {
Console.WriteLine ("loopRes.LowestBreakIteration.Value = " + loopRes.LowestBreakIteration.Value);
}
}

根据我在互联网上的阅读,我可以找到 Parallel.For 和 Parallel.Foreach 的 2 个属性

  1. 已完成
  2. 最低中断迭代

对我来说,第一个属性运行良好。但是当涉及到 3/0 的情况时,它会给出除以零的错误。所以第二个 if 循环应该给我 LowestBreakIteration 的数量,但它抛出了一个错误。如果有人遇到同样的问题并解决了,请告诉我!!

另请说明这两个属性的主要用途是什么。在什么情况下会有帮助。

希望很快收到某人的来信。

最佳答案

这是因为它抛出了一个异常,稍微改变一下你的循环:

public static void Main (string[] args) 
{
int k = 0;
int i = 3;
var loopRes = Parallel.For (0, 20, (J, loopState) =>
{
try { k = i / J; }
catch { loopState.Break(); }
Console.WriteLine ("Result After division " + J + " = " + k);
}
);

if (loopRes.IsCompleted) {
Console.WriteLine ("Loop was successful");
}
if (loopRes.LowestBreakIteration.HasValue) {
Console.WriteLine ("loopRes.LowestBreakIteration.Value = " + loopRes.LowestBreakIteration.Value);
}
}

关于c# - Parallel.For 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12838728/

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