Skip to content

Commit 1a6a4f3

Browse files
authored
ConcurrentQueue<T> F# snippet (dotnet#8856)
1 parent 7f98e48 commit 1a6a4f3

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//<snippet1>
2+
open System
3+
open System.Collections.Concurrent
4+
open System.Threading
5+
open System.Threading.Tasks
6+
7+
// Demonstrates:
8+
// ConcurrentQueue<T>.Enqueue()
9+
// ConcurrentQueue<T>.TryPeek()
10+
// ConcurrentQueue<T>.TryDequeue()
11+
12+
// Construct a ConcurrentQueue.
13+
let cq = ConcurrentQueue<int>()
14+
15+
// Populate the queue.
16+
for i = 0 to 9999 do
17+
cq.Enqueue i
18+
19+
// Peek at the first element.
20+
let mutable result = 0
21+
22+
if cq.TryPeek &result |> not then
23+
printfn "CQ: TryPeek failed when it should have succeeded"
24+
elif result <> 0 then
25+
printfn $"CQ: Expected TryPeek result of 0, got {result}"
26+
27+
let mutable outerSum = 0
28+
// An action to consume the ConcurrentQueue.
29+
let action =
30+
Action(fun () ->
31+
let mutable localSum = 0
32+
let mutable localValue = 0
33+
34+
while cq.TryDequeue &localValue do
35+
localSum <- localSum + localValue
36+
37+
Interlocked.Add(&outerSum, localSum) |> ignore)
38+
39+
// Start 4 concurrent consuming actions.
40+
Parallel.Invoke(action, action, action, action)
41+
42+
printfn $"outerSum = {outerSum}, should be 49995000"
43+
//</snippet1>
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+
<PropertyGroup>
3+
<OutputType>Exe</OutputType>
4+
<TargetFramework>net7.0</TargetFramework>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<Compile Include="concqueue.fs" />
9+
</ItemGroup>
10+
</Project>

xml/System.Collections.Concurrent/ConcurrentQueue`1.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
The following example shows how to use a <xref:System.Collections.Concurrent.ConcurrentQueue%601> to enqueue and dequeue items:
104104
105105
:::code language="csharp" source="~/snippets/csharp/System.Collections.Concurrent/ConcurrentQueueT/Overview/concqueue.cs" id="Snippet1":::
106+
:::code language="fsharp" source="~/snippets/fsharp/System.Collections.Concurrent/ConcurrentQueueT/Overview/concqueue.fs" id="Snippet1":::
106107
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.collections.concurrent.concurrentqueue/vb/concqueue.vb" id="Snippet1":::
107108
108109
]]></format>

0 commit comments

Comments
 (0)