从嵌套的Parallel.Foreach中的函数返回

时间:2013-09-09 13:28:57

标签: c# for-loop task-parallel-library

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

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;
}

返回true的替代语句是什么,将退出此函数?

1 个答案:

答案 0 :(得分:1)

由于两个循环可以在不同的线程上执行,因此必须在控制线程和处理ForEach调用的运行线程之间引入共享状态。在这种情况下,布尔值可以是assumed to be atomic updateable and therefor threadsafe so no locking is needed

在if条件中将result bool设置为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;
}