ConcurrentDictionary<T>とイミュータブルコレクション
スレッドセーフな更新にはConcurrentDictionary を使い、読み取り専用ビューやcopy-on-writeによるシンプルなイミュータブル化を学びます。
「ConcurrentDictionary<T>とイミュータブルコレクション」はCoddyKit上の無料C# Academyレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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>とイミュータブルコレクション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、C# Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 C# Academyコースには全3レッスンが含まれています。
「ConcurrentDictionary<T>とイミュータブルコレクション」で何を学びますか?
スレッドセーフな更新にはConcurrentDictionary を使い、読み取り専用ビューやcopy-on-writeによるシンプルなイミュータブル化を学びます。 ブラウザで直接実行するハンズオンコードでC# Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
C# Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのC# Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。
「ConcurrentDictionary<T>とイミュータブルコレクション」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このC# Academyレッスンでコードを書いて実行できますか?
はい。すべてのC# Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- HashSet 、SortedSet 、Queue 、Stack
- ConcurrentDictionary とイミュータブルコレクション
- 等価性とハッシュ(値と参照)