Skip to content

Commit 7f98e48

Browse files
authored
ConcurrentBag<T> F# snippets (dotnet#8854)
1 parent 481db8d commit 7f98e48

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//<snippet1>
2+
module ConcurrentBagDemo
3+
4+
open System.Collections.Concurrent
5+
open System.Threading.Tasks
6+
open System.Threading
7+
8+
// Demonstrates:
9+
// ConcurrentBag<T>.Add()
10+
// ConcurrentBag<T>.IsEmpty
11+
// ConcurrentBag<T>.TryTake()
12+
// ConcurrentBag<T>.TryPeek()
13+
14+
// Add to ConcurrentBag concurrently
15+
let cb = ConcurrentBag<int>()
16+
17+
let bagAddTasks =
18+
[| for i = 0 to 499 do
19+
let numberToAdd = i
20+
task { cb.Add numberToAdd } :> Task |]
21+
22+
// Wait for all tasks to complete
23+
Task.WaitAll bagAddTasks
24+
25+
// Consume the items in the bag
26+
let mutable itemsInBag = 0
27+
28+
let bagConsumeTasks =
29+
[| while not cb.IsEmpty do
30+
task {
31+
let mutable item = 0
32+
33+
if cb.TryTake &item then
34+
printfn $"{item}"
35+
Interlocked.Increment &itemsInBag |> ignore
36+
}
37+
:> Task |]
38+
39+
Task.WaitAll bagConsumeTasks
40+
41+
printfn $"There were {itemsInBag} items in the bag"
42+
43+
// Checks the bag for an item
44+
// The bag should be empty and this should not print anything
45+
let mutable unexpectedItem = 0
46+
47+
if cb.TryPeek &unexpectedItem then
48+
printfn "Found an item in the bag when it should be empty"
49+
//</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="concbag.fs" />
9+
</ItemGroup>
10+
</Project>

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@
105105
The following example shows how to add and remove items from a <xref:System.Collections.Concurrent.ConcurrentBag%601>:
106106
107107
:::code language="csharp" source="~/snippets/csharp/System.Collections.Concurrent/ConcurrentBag/concbag.cs" id="Snippet1":::
108+
:::code language="fsharp" source="~/snippets/fsharp/System.Collections.Concurrent/ConcurrentBag/concbag.fs" id="Snippet1":::
108109
:::code language="vb" source="~/snippets/visualbasic/api/system.collections.concurrent/concurrentbag/concbag.vb" id="Snippet1":::
109110
110111
]]></format>

0 commit comments

Comments
 (0)