獲取集合已修改;枚舉操作可能不會執行。例外獲取收藏已修改;枚舉操作可能不會執行。異常
代碼:
public static string GetValue(List<StateBag> stateBagList, string name)
{
string retValue = string.Empty;
if (stateBagList != null)
{
foreach (StateBag stateBag in stateBagList)
{
if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
retValue = stateBag.Value;
}
}
}
return retValue;
}
得到這個例外有一段時間沒有時間每次都在這個地方。
堆棧跟蹤:
在System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource 資源)
在System.Collections.Generic.List`1.Enumerator.MoveNextRare()
的系統。 Collections.Generic.List`1.Enumerator.MoveNext()
at Tavisca.TravelNxt.Shared.Entities.StateBag.GetValue(List`1 stateBagList,String nam E)
@no一個我已經嘗試了下面的代碼,但仍然得到例外
代碼:
class StateBag
{
public string Name;
public string Value;
}
class Program
{
static List<StateBag> _concurrent = new List<StateBag>();
static void Main()
{
var sw = new Stopwatch();
try
{
sw.Start();
Thread thread1 = new Thread(new ThreadStart(A));
Thread thread2 = new Thread(new ThreadStart(B));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
sw.Stop();
}
catch (Exception ex)
{
}
Console.WriteLine("Average: {0}", sw.ElapsedTicks);
Console.ReadKey();
}
private static Object thisLock = new Object();
public static string GetValue(List<StateBag> stateBagList, string name)
{
string retValue = string.Empty;
if (stateBagList != null)
{
lock (thisLock)
{
foreach (StateBag stateBag in stateBagList)
{
if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
retValue = stateBag.Value;
}
}
}
}
return retValue;
}
static void A()
{
for (int i = 0; i < 5000; i++)
{
_concurrent.Add(new StateBag() { Name = "name" + i, Value = i.ToString() });
}
}
static void B()
{
for (int i = 0; i < 5000; i++)
{
var t = GetValue(_concurrent, "name" + i);
}
}
}
傳遞給此方法的stateBagList可能會在其他地方更改。 –
我猜想這個方法可能是從1個線程調用的,而List則是從另一個線程同時修改的。 – Baldrick
我建議你只爲stateBagList使用一個ConcurrentDictionary,並將它的Name(如果它是唯一的)鍵入。這將比連續搜索List更高效,並且將消除對自己的鎖定邏輯的需要。 – Baldrick