简体   繁体   English

如何降低无限循环的风险?

[英]How do I mitigate the risk of an infinite loop?

We are looking through our code trying to identify high CPU usage, and I am looking at several areas where we use while loops. 我们正在查看我们的代码,试图识别高CPU使用率,我正在研究我们使用while循环的几个方面。 I would like to take the risk of infinite loops out of the code shown below, but I am not sure what the best solution would be. 我想从下面显示的代码中冒出无限循环的风险,但我不确定最佳解决方案是什么。

IDictionaryEnumerator codeEnumerator = Resources.Error_Codes.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true).GetEnumerator();
IDictionaryEnumerator messageEnumerator = Resources.Error_Messages.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true).GetEnumerator();


bool codeDone = false;
bool messageDone = false;

while (codeEnumerator.MoveNext() && !codeDone)
{
    string value = codeEnumerator.Value.ToString();
    if (value == failedResponse.Code.ToString())
    {
        key = codeEnumerator.Key.ToString();
        codeDone = true;
    }
}

while (messageEnumerator.MoveNext() && !messageDone)
{
    if (messageEnumerator.Key.ToString() == key)
    {
        message = messageEnumerator.Value.ToString();
        messageDone = true;
    }
}

Assuming that the underlying sequence are finite, not infinite, ( which you have said is the case ) then the loops will not run forever. 假设底层序列是有限的,而不是无限的( 你已经说过就是这种情况 )那么循环将不会永远运行。

Eventually you can be sure that one of the following things will happen: 最终你可以确定会发生以下事情之一:

  1. The if will be true for a given item, thus setting the boolean and breaking out of the loop. 对于给定的项, if将为true,从而设置布尔值并打破循环。

  2. You will advance to the end of the sequence, thus resulting in MoveNext being false. 您将前进到序列的末尾,从而导致MoveNext为false。

  3. An exception will be thrown from somewhere, such as from the underlying collection being modified by another thread, by a null value in the sequence, or anything else. 将从某处抛出异常,例如从另一个线程修改的底层集合,序列中的空值或其他任何内容。 As you have no try/catch, this will break you out of the loop. 因为你没有尝试/捕获,这将使你脱离循环。

In particular, since each iteration of the loop must advance the iterator (due to MoveNext ) you can be sure that you will eventually end. 特别是,由于循环的每次迭代都必须推进迭代器(由于MoveNext ),因此可以确定最终会结束。

Looking at your code and trying to figure out what your dictionaries are actually named, I think you're looking for something like this: 查看您的代码并试图找出您的字典实际命名的内容,我认为您正在寻找类似这样的内容:

var key = Error_Codes.FirstOrDefault(kvp => kvp.Value.ToString = 
    failedResponse.Code.ToString()).Select(kvp => kvp.Key);
string message = string.Empty;
if(null != key)
    message = Error_Messages[key];

This assumes your dictionaries are Error_Codes and Error_Messages. 这假设您的词典是Error_Codes和Error_Messages。

As Eric pointed out in the comments, there were issues with the way you were using iterators and dictionaries. 正如Eric在评论中指出的那样,你使用迭代器和字典的方式存在问题。 This does away with the iterator problems, but this still isn't an ideal way to use dictionaries. 这消除了迭代器问题,但这仍然不是使用字典的理想方式。

If you have a unique list of error messages and error code keys, then you could have a dictionary that maps the two together. 如果您有一个唯一的错误消息列表和错误代码键,那么您可以使用一个字典将两者映射到一起。 Alternatively, you could combine the dictionaries with a common key set for the dictionary key, and a tuple of error codes and error messages as the dictionary values. 或者,您可以将字典与字典键的公用键集以及错误代码和错误消息的元组组合作为字典值。

You could start a timer/other thread that sets a second contidion to false if the loop takes more than x time. 你可以启动一个定时器/其他线程,如果循环时间超过x时间,则将第二个contidion设置为false。 But i dont think that this is a clean solution either. 但我不认为这也是一个干净的解决方案。

You could add a counter that counts down in the while loop. 您可以添加一个在while循环中倒计时的计数器。 Set the counter real high to a value like 100 or so and When the counter reaches zero, exit the loop. 将计数器实数高设置为大约100左右的值,当计数器达到零时,退出循环。 It means that its possible it might terminate before the operation is completely carried out, but it means it will eventually exit. 这意味着它可能在操作完全执行之前终止,但这意味着它最终会退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决此无限循环/ StackOverFlow错误? - How do I fix this infinite loop / StackOverFlow error? 我如何修复此代码进入的无限循环? - How do i fix the infinite loop that this code gets itself into? 覆盖虚拟属性时如何避免无限循环? - How do I avoid an infinite loop when overriding a virtual property? 如何在无限循环中使用线程锁? - How do i use thread locks in an infinite loop? 如何检测代码中发生的无限循环? - How do I detect an infinite loop occuring in my code? 由于网页的缓存版本,我如何消除安全风险 - how do i remove the security risk, due to cached version of page 如何在C#中执行无限循环,每次迭代延迟1分钟? - How do I do an infinite loop in C# with a 1 minute delay per iteration? 如何在不引起无限循环的情况下从form2引用form1? - How do I refrence form1 from form2 without causing an infinite loop? 如何创建一个无限循环,问题在回答时将答案分类为 3 个不同数组中的 1 个? - How do I create an infinite loop with a question that when answered, categorizes the answer into 1 of 3 different arrays? 当没有匹配时,你如何摆脱无限循环? - How do you get out of infinite loop when there's no match?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM