我知道一般来说List不是线程安全的,但是如果线程从不在列表上执行任何其他操作(例如遍历它),那么简单地将项添加到列表中是否有什么问题?
例:
List<object> list = new List<object>();
Parallel.ForEach(transactions, tran =>
{
list.Add(new object());
});
Run Code Online (Sandbox Code Playgroud) 除了Concurrent Collections是命名空间还是一个类之外,命名空间中SynchronizedCollection<T>的并发集合如何System.Collections.Concurrent相互不同SynchronizedCollection<T>?
SynchronizedCollection<T>并发集合中的所有类都提供了线程安全的集合.我如何决定何时使用其中一个,为什么?
c# collections .net-4.0 thread-safety concurrent-collections
我使用以下代码
var processed = new List<Guid>();
Parallel.ForEach(items, item =>
{
processed.Add(SomeProcessingFunc(item));
});
Run Code Online (Sandbox Code Playgroud)
上面的代码线程是否安全?处理后的列表是否有可能被破坏?或者我应该在添加之前使用锁?
var processed = new List<Guid>();
Parallel.ForEach(items, item =>
{
lock(items.SyncRoot)
processed.Add(SomeProcessingFunc(item));
});
Run Code Online (Sandbox Code Playgroud)
谢谢.
我想知道,假设我有一个 ConcurrentBag 封装在这样的对象中
class Package
{
private ConcurrentBag<string> myList;
public string title {get; private set;}
public string description {get; private set;}
public Package(string title,string description)
{
myList = new ConcurrentBag<string>();
this.title = title;
this.description = description;
}
public override string ToString()
{
return title + " " + description;
}
}
Run Code Online (Sandbox Code Playgroud)
我将如何返回我的 ConcurrentBag 的只读版本?
我在一个类中有这个代码:
private static MyObject _locker = new MyObject();
...
lock (_locker)
{
...
_locker = new MyObject();
...
}
Run Code Online (Sandbox Code Playgroud)
它会锁定_locker吗?
我有C#.Net 4代码,它添加到Parallel.For中的List <>.如果这是线程安全的话,我找不到明确的答案.如果不安全有哪些替代方案?
static List<int> Calculate(List<string[]> numbers)
{
List<int> sums = new List<int>();
Parallel.ForEach(numbers,
(nums) =>
{
int sum = 0;
for (int i = 0; i < nums.Length; i++)
sum += Convert.ToInt32( nums[i]);
// is this thread safe or not???
sums.Add(sum);
});
sums.Sort();
return sums;
}
Run Code Online (Sandbox Code Playgroud)