0Pricing
C# Academy · 课时

ConcurrentDictionary<T> 与不可变集合

使用 ConcurrentDictionary 实现线程安全的更新,并学习简单的不可变方案:只读视图和写时复制。

ConcurrentDictionary<T> 与不可变集合 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

线程安全与不可变性的基础

本课内容:

  • ConcurrentDictionary<TKey,TValue>:支持来自多个线程的安全更新
  • 只读视图与真正的不可变性
  • 写时复制:实现简单安全性的思路

原子操作:GetOrAdd/AddOrUpdate

请使用 GetOrAdd 和 AddOrUpdate 执行原子操作,并使用 TryGetValue 安全读取。

using System;
using System.Collections.Concurrent;

public class Program
{
  public static void Main(string[] args)
  {
    ConcurrentDictionary<string, int> counts = new ConcurrentDictionary<string, int>();

    // Add if missing
    int a = counts.GetOrAdd("apple", 0); // 0
    // Increment safely
    int newVal = counts.AddOrUpdate("apple", 1, (key, oldValue) => oldValue + 1);

    Console.WriteLine("apple was " + a + ", now " + newVal);

    int value;
    bool ok = counts.TryGetValue("apple", out value);
    Console.WriteLine("Has apple? " + ok + " -> " + value);
  }
}

无竞态递增的思路

AddOrUpdate 会通过原子更新避免经典的读取-修改-写入竞态。

using System;
using System.Collections.Concurrent;

public class Program
{
  static int Inc(int oldValue) { return oldValue + 1; }

  public static void Main(string[] args)
  {
    ConcurrentDictionary<string, int> clicks = new ConcurrentDictionary<string, int>();

    // Simulate multiple updates
    for (int i = 0; i < 5; i++)
    {
      clicks.AddOrUpdate("home", 1, delegate(string k, int v) { return Inc(v); });
    }

    Console.WriteLine("home clicks = " + clicks["home"]); // 5 (starting at 1 then +4)
  }
}

只读视图(并非不可变)

AsReadOnly 返回的是只读视图,而不是真正不可变的集合:源的更改会显示在该视图中。

using System;
using System.Collections.Generic;

public class Program
{
  public static void Main(string[] args)
  {
    List<string> items = new List<string>(new string[] { "A", "B" });
    var ro = items.AsReadOnly(); // ReadOnlyCollection<string>

    foreach (string s in ro) Console.WriteLine(s); // A, B

    // ro.Add("C"); // not available: read-only view has no Add

    // But changing the source list reflects in the view:
    items.Add("C");
    Console.WriteLine("After source change:");
    foreach (string s in ro) Console.WriteLine(s); // A, B, C
  }
}

写时复制快照

写时复制:发生更改时返回一个新列表。保留旧列表的调用方可以看到稳定的快照。

using System;
using System.Collections.Generic;

public class Program
{
  static List<int> AddWithoutTouchingOriginal(List<int> original, int item)
  {
    // create a copy and modify the copy
    List<int> copy = new List<int>(original);
    copy.Add(item);
    return copy;
  }

  public static void Main(string[] args)
  {
    List<int> a = new List<int>(new int[] { 1, 2 });
    List<int> b = AddWithoutTouchingOriginal(a, 3);

    Console.WriteLine("Original:");
    foreach (int x in a) Console.WriteLine(x); // 1,2

    Console.WriteLine("Copy:");
    foreach (int x in b) Console.WriteLine(x); // 1,2,3
  }
}

提示与权衡

提示:

  • 对于共享计数器/缓存,请使用 ConcurrentDictionary。
  • AsReadOnly 可以防止使用者意外修改数据。
  • 需要稳定视图时,请在修改列表之前先复制列表。
  • 真正的不可变集合位于 System.Collections.Immutable(包)中;为使代码保持独立,这里不使用它们。

线程安全字典的选择

快速检查:哪个集合支持线程安全的添加/更新,而无需外部锁?

总结

总结:使用 ConcurrentDictionary 进行并发更新。向调用方提供只读视图,并在需要稳定快照时使用写时复制。

常见问题解答

「ConcurrentDictionary<T> 与不可变集合」课时是免费的吗?

是的 — 「ConcurrentDictionary<T> 与不可变集合」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「ConcurrentDictionary<T> 与不可变集合」这节课中我会学到什么?

使用 ConcurrentDictionary 实现线程安全的更新,并学习简单的不可变方案:只读视图和写时复制。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「ConcurrentDictionary<T> 与不可变集合」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. HashSet 、SortedSet 、Queue 、Stack
  2. ConcurrentDictionary 与不可变集合
  3. 相等性与哈希(值与引用)
← 返回 C# Academy