相关疑难解决方法(0)

List.Add()线程安全

我知道一般来说List不是线程安全的,但是如果线程从不在列表上执行任何其他操作(例如遍历它),那么简单地将项添加到列表中是否有什么问题?

例:

List<object> list = new List<object>();
Parallel.ForEach(transactions, tran =>
{
    list.Add(new object());
});
Run Code Online (Sandbox Code Playgroud)

c# asp.net

79
推荐指数
6
解决办法
4万
查看次数

SynchronizedCollection <T>和其他并发集合有什么区别?

除了Concurrent Collections是命名空间还是一个类之外,命名空间中SynchronizedCollection<T>的并发集合如何System.Collections.Concurrent相互不同SynchronizedCollection<T>

SynchronizedCollection<T>并发集合中的所有类都提供了线程安全的集合.我如何决定何时使用其中一个,为什么?

c# collections .net-4.0 thread-safety concurrent-collections

51
推荐指数
2
解决办法
2万
查看次数

列出<T>线程安全

我使用以下代码

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)

谢谢.

c# list parallel-extensions task-parallel-library c#-4.0

29
推荐指数
3
解决办法
1万
查看次数

返回只读并发列表

我想知道,假设我有一个 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 的只读版本?

.net c#

5
推荐指数
1
解决办法
1047
查看次数

C#锁定在锁定块中重新分配的对象

我在一个类中有这个代码:

private static MyObject _locker = new MyObject();

...

lock (_locker)
{
     ...
     _locker = new MyObject();
     ...
}
Run Code Online (Sandbox Code Playgroud)

它会锁定_locker吗?

c# multithreading locking

4
推荐指数
1
解决办法
705
查看次数

List <>线程的c#用法是否安全?

我有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)

c#

0
推荐指数
1
解决办法
3918
查看次数