1

这里是代码片段,我想在条件满足时退出函数。我怎样才能做到这一点?

bool MyNestedFunction()
{
   Parallel.Foreach (ListofStrings_A, OuterString =>//loopA
   {

       Parallel.Foreach (ListofStrings_B, InnerString //loopB
       {
          string FirstTemperedString = Temperedstring.Substring(0,Temperedstring.LastIndexOf(" "));
          string LastTemperedString = Temperedstring.Substring(Temperedstring.IndexOf(" "));

          string FirstOuterString = OuterString.Substring(0, OuterString.LastIndexOf(" "));
          string LastOuterString = OuterString.Substring( OuterString.IndexOf(" "));

          if (FirstTemperedString.Equals(FirstOuterString) || LastTemperedString.Equals(LastOuterString))
          {
                return true; // I want to return from the function (MyNestedFunction)here
                // What will be the alternate code here
          }
        });
    })

    return false;
}

return true 的替代语句将退出此函数?

4

1 回答 1

3

由于这两个循环可以在不同的线程上执行,因此您必须在控制线程和处理ForEach调用的运行线程之间引入共享状态。在这种情况下,可以假定布尔值是可原子更新的,因此是线程安全的,因此不需要锁定

在 if 条件中,将resultbool 设置为 true,然后调用state.Stop();以指示外循环应该结束。当它确实控制返回给调用线程时result,现在为真,并且该值返回给调用者。

bool MyNestedFunction()
{
   bool result = false; // shared state!

   Parallel.ForEach (ListofStrings_A, (OuterString, state) =>//loopA
   {

       Parallel.ForEach (ListofStrings_B, InnerString => //loopB
       {
          string FirstTemperedString = Temperedstring.Substring(0,Temperedstring.LastIndexOf(" "));
          string LastTemperedString = Temperedstring.Substring(Temperedstring.IndexOf(" "));

          string FirstOuterString = OuterString.Substring(0, OuterString.LastIndexOf(" "));
          string LastOuterString = OuterString.Substring( OuterString.IndexOf(" "));


          if (FirstTemperedString.Equals(FirstOuterString) || LastTemperedString.Equals(LastOuterString))
          {
                result = true; // set the return value
                state.Stop(); // signal to Stop the ForEach on all Threads
          }
        });
    });

    return result;
}
于 2014-02-11T22:17:18.280 回答