枚举操作可能无法执行

枚举操作可能无法执行

本文介绍了收集被修改;枚举操作可能无法执行。锁正在被使用到处如何可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个只有我编写和使用的小程序。

This is a small program that only i am writing and using.

现在我要写所有领域的代码,我使用的哈希集导致这个问题

Now i am going to write code of all areas where i use the hashset that caused this problem

我不明白这是怎么可能的。此项仅在MainWindow中使用

I don't understand how this is possible. This item is being used only at MainWindow

hsProxyList是一个哈希表

hsProxyList is a hashset

  HashSet<string> hsProxyList = new HashSet<string>();

在下面的迭代中发生错误

the error happened at below iteration

 lock (hsProxyList)
            {
    int irRandomProxyNumber = GenerateRandomValue.GenerateRandomValueMin(hsProxyList.Count, 0);
    int irLocalCounter = 0;
    foreach (var vrProxy in hsProxyList)
    {
       if (irLocalCounter == irRandomProxyNumber)
       {
       srSelectedProxy = vrProxy;
       break;
       }
         irLocalCounter++;
       }
    }
}

hsProxyList

The other places where i use hsProxyList

我不会锁定对象,当我得到它的计数 - 我认为这不会导致任何错误,但可能不正确 - 不是非常重要

I don't lock the object when i am getting its count - i suppose this would not cause any error but may be not correct - not fatally important

 lblProxyCount.Content = "remaining proxy count: " + hsProxyList.Count;

lock (hsProxyList)
{
    hsProxyList.Remove(srSelectedProxy);
}

lock (hsProxyList)
{
    hsProxyList = new HashSet<string>();
    foreach (var vrLine in File.ReadLines(cmbBoxSelectProxy.SelectedItem.ToString()))
    {
        hsProxyList.Add(vrLine);
    }
}

可以看出,这是一个多线程软件。所有hsProxyList都在MainWindow.xaml.cs中使用 - 它是一个C#WPF应用程序

As can be seen i am using lock everywhere. This is a multi threading software. All hsProxyList is being used in MainWindow.xaml.cs - it is a C# WPF application

推荐答案

问题是你有

lock (hsProxyList)
{
    hsProxyList = new HashSet<string>();
    // etc
}

当你执行 hsProxyList = new HashSet< string>(); 时改变对象,所以变量hsProxyList引用的对象不再被锁定。

All locks are on a particular object, however you're changing the object when you do hsProxyList = new HashSet<string>(); so the object that the variable hsProxyList refers to is no longer locked.

这篇关于收集被修改;枚举操作可能无法执行。锁正在被使用到处如何可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:13