Skip to content

Commit 79232db

Browse files
authored
Merge pull request #7 from ibrahimatay/Concurrent-Collections
Concurrent collections
2 parents 081b398 + 77555fa commit 79232db

4 files changed

Lines changed: 143 additions & 5 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
</Project>

ConcurrentCollections/Program.cs

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
using System.Collections.Concurrent;
2+
3+
namespace ConcurrentCollections;
4+
5+
// System.Collections.Concurrent Namespace
6+
// https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent?view=net-9.0
7+
8+
static class Program
9+
{
10+
public static void Main()
11+
{
12+
//ConcurrentDictionaryExample();
13+
//ConcurrentBagExample();
14+
//ThreadSafeListLikeAsConcurrentList();
15+
//ConcurrentQueueExample();
16+
//ConcurrentStackExample();
17+
//BlockingCollectionExample();
18+
}
19+
20+
static readonly ConcurrentDictionary<int, string> Dictionary = new ConcurrentDictionary<int, string>();
21+
static void ConcurrentDictionaryExample()
22+
{
23+
Parallel.For(0, 100, i =>
24+
{
25+
var added = Dictionary.TryAdd(i, $"Value-{i}");
26+
if (added)
27+
{
28+
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} added key {i}");
29+
}
30+
});
31+
32+
Console.WriteLine("\nAll items in dictionary:");
33+
foreach (var kvp in Dictionary)
34+
{
35+
Console.WriteLine($"{kvp.Key} => {kvp.Value}");
36+
}
37+
}
38+
39+
static readonly ConcurrentBag<int> Bag = new ConcurrentBag<int>();
40+
static void ConcurrentBagExample()
41+
{
42+
Parallel.For(0, 100, i =>
43+
{
44+
Bag.Add(i);
45+
});
46+
47+
Console.WriteLine($"Count: {Bag.Count}");
48+
}
49+
50+
static readonly List<int> List = new List<int>();
51+
static readonly object Locker = new object();
52+
static void ThreadSafeListLikeAsConcurrentList()
53+
{
54+
Parallel.For(0, 100, i =>
55+
{
56+
lock (Locker)
57+
{
58+
List.Add(i);
59+
}
60+
});
61+
62+
Console.WriteLine($"Count: {List.Count}");
63+
}
64+
65+
static readonly ConcurrentQueue<int> Queue = new ConcurrentQueue<int>();
66+
static void ConcurrentQueueExample()
67+
{
68+
Parallel.For(0, 100, i =>
69+
{
70+
Queue.Enqueue(i);
71+
});
72+
73+
Console.WriteLine($"Queue Count After Enqueue: {Queue.Count}");
74+
75+
while (Queue.TryDequeue(out var result))
76+
{
77+
Console.WriteLine($"Dequeued: {result}");
78+
}
79+
}
80+
81+
static readonly ConcurrentStack<int> Stack = new ConcurrentStack<int>();
82+
static void ConcurrentStackExample()
83+
{
84+
Parallel.For(0, 100, i =>
85+
{
86+
Stack.Push(i);
87+
});
88+
89+
Console.WriteLine($"Stack Count After Push: {Stack.Count}");
90+
91+
while (Stack.TryPop(out var result))
92+
{
93+
Console.WriteLine($"Popped: {result}");
94+
}
95+
}
96+
97+
static readonly BlockingCollection<int> Blocking = new BlockingCollection<int>(boundedCapacity: 10);
98+
static void BlockingCollectionExample()
99+
{
100+
var producer = Task.Run(() =>
101+
{
102+
for (int i = 0; i < 20; i++)
103+
{
104+
Blocking.Add(i);
105+
Console.WriteLine($"Produced: {i}");
106+
}
107+
Blocking.CompleteAdding();
108+
});
109+
110+
var consumer = Task.Run(() =>
111+
{
112+
foreach (var item in Blocking.GetConsumingEnumerable())
113+
{
114+
Console.WriteLine($"Consumed: {item}");
115+
Thread.Sleep(100); // Simulate work
116+
}
117+
});
118+
119+
Task.WaitAll(producer, consumer);
120+
}
121+
}

CsharpLangExamples.sln

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreateUnboundedPrioritized"
9999
EndProject
100100
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KeyedServices", "KeyedServices\KeyedServices.csproj", "{6ACD6B38-B2B1-469D-AE58-E5D67AF4839E}"
101101
EndProject
102+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConcurrentCollections", "ConcurrentCollections\ConcurrentCollections.csproj", "{E40B458B-5337-47D9-8FC1-2C5167485271}"
103+
EndProject
102104
Global
103105
GlobalSection(SolutionConfigurationPlatforms) = preSolution
104106
Debug|Any CPU = Debug|Any CPU
@@ -289,6 +291,10 @@ Global
289291
{6ACD6B38-B2B1-469D-AE58-E5D67AF4839E}.Debug|Any CPU.Build.0 = Debug|Any CPU
290292
{6ACD6B38-B2B1-469D-AE58-E5D67AF4839E}.Release|Any CPU.ActiveCfg = Release|Any CPU
291293
{6ACD6B38-B2B1-469D-AE58-E5D67AF4839E}.Release|Any CPU.Build.0 = Release|Any CPU
294+
{E40B458B-5337-47D9-8FC1-2C5167485271}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
295+
{E40B458B-5337-47D9-8FC1-2C5167485271}.Debug|Any CPU.Build.0 = Debug|Any CPU
296+
{E40B458B-5337-47D9-8FC1-2C5167485271}.Release|Any CPU.ActiveCfg = Release|Any CPU
297+
{E40B458B-5337-47D9-8FC1-2C5167485271}.Release|Any CPU.Build.0 = Release|Any CPU
292298
EndGlobalSection
293299
GlobalSection(SolutionProperties) = preSolution
294300
HideSolutionNode = FALSE

README.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,12 @@ Here are examples of C# programming to help you stay up-to-date with the latest
9090

9191
### C# 4 & others
9292

93-
| Feature | Description |
94-
|---------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
95-
|[Dynamic types](DynamicTypes/Program.cs) | Investigates dynamic types using `dynamic`, `ExpandoObject`, and `Activator.CreateInstance`; compares runtime and compile-time behaviors. Includes extension methods, overload resolution, and dynamic collections. |
96-
|[Multicast Delegates](MulticastDelegates/Program.cs) | Demonstrates combining multiple methods into a single delegate instance using multicast delegates. Suitable for event handling, callback chaining, and modular invocation patterns. |
97-
|[DebuggerDisplay](DebuggerDisplay/Program.cs) | Uses `DebuggerDisplay` to customize object visualization in the debugger. Displays a formatted summary during debugging instead of relying on `ToString()`, reducing unnecessary property expansions. |
93+
| Feature | Description |
94+
|-----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
95+
| [Dynamic types](DynamicTypes/Program.cs) | Investigates dynamic types using `dynamic`, `ExpandoObject`, and `Activator.CreateInstance`; compares runtime and compile-time behaviors. Includes extension methods, overload resolution, and dynamic collections. |
96+
| [Multicast Delegates](MulticastDelegates/Program.cs) | Demonstrates combining multiple methods into a single delegate instance using multicast delegates. Suitable for event handling, callback chaining, and modular invocation patterns. |
97+
| [DebuggerDisplay](DebuggerDisplay/Program.cs) | Uses `DebuggerDisplay` to customize object visualization in the debugger. Displays a formatted summary during debugging instead of relying on `ToString()`, reducing unnecessary property expansions. |
98+
| [ConcurrentCollections](ConcurrentCollections/Program.cs) | Demonstrates how to use .NET's thread-safe collections such as `ConcurrentDictionary`, `ConcurrentBag`, `ConcurrentQueue`, `ConcurrentStack`, and `BlockingCollection` in multi-threaded scenarios. Each collection is optimized for different concurrent data access needs (FIFO, LIFO, producer-consumer, etc.). The code provides simple and observable scenarios using `Parallel.For`, `lock`, and `Console.WriteLine`. |
9899

99100
## Notes
100101
- [Which C# version is included in which framework version?](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version)

0 commit comments

Comments
 (0)