我有以下代码:
public static ConcurrentBag<MyClass> all = new ConcurrentBag<MyClass>();
public static void Load()
{
all.Add("first");
all.Add("second");
all.Add("third");
all.Add("fourth");
foreach (MyClass item in all)
{
item.Load();
}
}它是否保证我将有“第一”项目在我的收藏(这是理想的)?
我可以这样迭代吗?还是我需要使用Parallel.ForEach?
发布于 2018-08-20 09:36:44
不能保证这些要素是独一无二的:
当订购不重要的时候,袋子对于存储物品很有用,而且与套装不同,袋子支持重复的东西。
发布于 2018-08-20 13:01:15
基于您的评论,您想要一个单例集合,并且似乎希望它在第一个调用之前加载,我已经使用懒惰创建了一个解决方案。或者,对于ConcurrentBag,您可以使用ImmutableList。
using System;
using System.Collections.Concurrent;
public class MyClass
{
public MyClass(string description)
{
}
public void Load()
{
}
}
public class MyClassLoader
{
public static Lazy<ConcurrentBag<MyClass>> allLazy = new Lazy<ConcurrentBag<MyClass>>(() =>
{
ConcurrentBag<MyClass> bag = new ConcurrentBag<MyClass>();
bag.Add(new MyClass("first"));
bag.Add(new MyClass("second"));
bag.Add(new MyClass("third"));
bag.Add(new MyClass("fourth"));
foreach (MyClass item in bag)
{
item.Load();
}
return bag;
}
);
public static void Load()
{
foreach (MyClass item in allLazy.Value)
{
// Do whatever you want
}
}
}https://stackoverflow.com/questions/51927687
复制相似问题