Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 添加到并发集合_C#_Multithreading_Concurrent Collections - Fatal编程技术网

C# 添加到并发集合

C# 添加到并发集合,c#,multithreading,concurrent-collections,C#,Multithreading,Concurrent Collections,在处理并发集合(例如ConcurrentDictionary)时,我应该使用TryAdd方法,还是只使用普通的旧索引赋值?我的意思是,TryAdd方法在添加时是否会阻塞,因此如果另一个线程试图删除该值,它将不得不等待添加完成?索引器的setter和add都在内部调用TryAdd public TValue this[TKey key] { get { /*Irrelevant*/ } set { if ((object) key == null) throw ne

在处理并发集合(例如ConcurrentDictionary)时,我应该使用TryAdd方法,还是只使用普通的旧索引赋值?我的意思是,TryAdd方法在添加时是否会阻塞,因此如果另一个线程试图删除该值,它将不得不等待添加完成?

索引器的setter和add都在内部调用TryAdd

public TValue this[TKey key]
{
  get { /*Irrelevant*/ }
  set
  {
    if ((object) key == null)
      throw new ArgumentNullException("key");
    TValue resultingValue;
    this.TryAddInternal(key, value, true, true, out resultingValue);
  }
}
添加方法:


索引器的setter和Add调用TryAdd都在内部

public TValue this[TKey key]
{
  get { /*Irrelevant*/ }
  set
  {
    if ((object) key == null)
      throw new ArgumentNullException("key");
    TValue resultingValue;
    this.TryAddInternal(key, value, true, true, out resultingValue);
  }
}
添加方法:


前缀try与线程安全无关。它只是Add的无异常版本。

前缀try与线程安全无关。它只是Add的无异常版本。

够了吗?没有线程安全的意义。够了吗?没有线程安全的概念。所以如果我希望我的代码是线程安全的,我应该怎么做?并发集合在默认情况下是线程安全的,所以我可以只使用索引赋值吗?所以,如果我希望我的代码是线程安全的,我应该怎么做?并发集合在默认情况下是线程安全的,所以我可以只使用索引分配吗?