在字典上使用锁定后的IndexOutOfBound

时间:2019-07-05 13:14:05

标签: c# dictionary locks

我从字典中收到indexOutOfBound错误,所以我在网上搜索,他们说这是线程安全的问题,因为我没有锁定字典,所以我在网上搜索并且不了解如何在字典上使用锁。但是令我惊讶的是,在字典上使用锁之后,代码仍然给出相同的错误。我在字典上实现锁定的方式可能会出错。

我通过以下链接进行参考:- https://social.msdn.microsoft.com/Forums/vstudio/en-US/c8a83d23-a62e-4e37-a902-8e229bf3c31f/indexoutofrangeexception-on-genericsdictionaryadd-method?forum=netfxbcl

c# Dictionary lookup throws "Index was outside the bounds of the array"

我从此链接中学到了锁:--- Correct way to lock the dictionary object

我已经通过类似于我的问题的链接,但是解决方案并不令人满意:C# Dictionary Index was outside the bounds of the array with lock

public class Pattern
{
    public int index { get; set; }
    public char character { get; set; }
    public Pattern(int index, char character)
    {
        this.index = index;
        this.character = character;
    }

}
class Solution4
{
    public String convert(String s, int numRows)
    {
        int stringLength = s.Length;


      string main = string.Empty;
        int counter = 1;
        int index = 1;
        bool Mode = true;
        Dictionary<int, Pattern> dict = new Dictionary<int, Pattern>();
        while (stringLength > 0)
        {
            lock (dict)
            {
                dict.Add(index, new Pattern(counter, s[index]));
            }
            if (Mode == true)
            {
                counter++;
            }
            else
            {
                counter--;
            }
            index++;
            if (counter == numRows)
            {
                Mode = false;
            }
            else if (counter == 1)
            {
                Mode = true;
            }
            stringLength--;
        }
        for (int i = 1; i <= 5; i++)
        {
            lock (dict)
            {
                foreach (var item in dict)
                {
                    if (item.Value.index == i)
                    {
                        main += item.Value.character;
                    }
                }
            }
        }
        return main;
    }
}

如果您发现我的错误或我做错了什么,我将为您提供很大的帮助。 预先感谢

0 个答案:

没有答案