我编写了一些类来使用SynchronizedCollection.
class MultithreadTesting
{
public readonly SynchronizedCollection<int> testlist = new SynchronizedCollection<int>();
public SynchronizedReadOnlyCollection<int> pubReadOnlyProperty
{
get
{
return new SynchronizedReadOnlyCollection<int>(testlist.SyncRoot, testlist);
}
}
public void Test()
{
int numthreads = 20;
Thread[] threads = new Thread[numthreads];
List<Task> taskList = new List<Task>();
for (int i = 0; i < numthreads / 2; i++)
{
taskList.Add(Task.Factory.StartNew(() =>
{
for (int j = 0; j < 100000; j++)
{
testlist.Add(42);
}
}));
}
for (int i = numthreads / 2; i < numthreads; i++)
{
taskList.Add(Task.Factory.StartNew(() =>
{
var sum = 0;
foreach (int num in pubReadOnlyProperty)
{
sum += num;
}
}));
}
Task.WaitAll(taskList.ToArray());
testlist.Clear();
}
}
运行它我使用
MultithreadTesting test = new MultithreadTesting();
while (true)
test.Test();
但是代码让我失望System.ArgumentException: 'Destination array was not long enough. Check destIndex and length, and the array's lower bounds.'
如果我尝试使用testlistin foreach,我会得到
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
然而,MSDN 告诉我们
SynchronizedReadOnlyCollection 类
提供一个线程安全的只读集合,其中包含泛型参数指定类型的对象作为元素。
MYYA
相关分类