PLINQ查询,需要知道执行了多少次迭代 [英] PLINQ query, need to know how many iterations performed

查看:267
本文介绍了PLINQ查询,需要知道执行了多少次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上做的是在一个字母组合序列上并行迭代,当我得到组合我想它被认为是一个胜利。我想从这个查询中获得所有的胜利(这是正确的),但诀窍是如何跟踪的胜利测试执行的次数(基本上返回true / false的方法,它赢了)。

what I'm basically doing is iterating in parallel over a sequence of letter combinations, when I get the combo I want it's considered a win. I want to get all the wins from this query (which it's doing correctly), but the trick has been how to keep track of the number of times the test for a win was executed (basically the method that returns true/false that it won).

我在类中创建一个实例变量,每次在组合测试执行时递增,但每次运行该进程时,此实例变量的编号。我发现这是一个线程问题,但我不知道如何解决它。

I'm creating an instance variable in the class that increments each time the test on the combo is performed, but each time I run the process I get a different number for this instance variable. I realize it's a threading issue, but I'm not sure how to resolve it.

这个命中的最大数量的限制,停止。如果我没有这个约束,我不需要知道组合运行的次数明显,因为它会运行所有的组合,但正如你所看到的,我需要打破查询,当我击中max

There's a max limit for the number of wins that when this is hit the query needs to stop. If I didn't have that constraint I wouldn't need to know the number of times a combo is run obviously, as it would run all the combos, but as you see I need to break out of the query when I hit the max limit.

public Results GetWinResults()
{
         ParallelQuery<string> winningCombos = from n in _nextCombination.GetNextCombo().AsParallel()                                          
                       where processNextCombo(n) // where there was a win
                       select n;

         List<string> wins = new List<string>();

         foreach (var winningCombo in winningCombos)
         {
               wins.Add(winningCombo);
               if (wins.Count == winsMaxLimit)
                  break;
         }

         return new Results { Wins = wins, CombosTried = totalCombosRun };
 }


 private bool processNextCombo(string combo)
 {
     totalCombosRun++;
     // do tests to see if combo was a winner
     if (didWin)
        return true;
     return false;
 }


推荐答案

href =http://msdn.microsoft.com/en-us/library/dd78zt0c%28v=vs.80%29.aspx =nofollow> Interlocked 类在线程安全中递增int时尚:

You can use the Interlocked class to increment an int in a threadsafe fashion:

 int totalCombosRun=0;

 private bool processNextCombo(string combo)
 {
     Interlocked.Increment(ref totalCombosRun);
     // do tests to see if combo was a winner
     if (didWin)
        return true;
     return false;
 }

这篇关于PLINQ查询,需要知道执行了多少次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆