File tree Expand file tree Collapse file tree 3 files changed +60
-0
lines changed
snippets/fsharp/System.Collections.Concurrent/ConcurrentBag
xml/System.Collections.Concurrent Expand file tree Collapse file tree 3 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
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>
Original file line number Diff line number Diff line change
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 >
Original file line number Diff line number Diff line change 105
105
The following example shows how to add and remove items from a <xref:System.Collections.Concurrent.ConcurrentBag%601>:
106
106
107
107
:::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":::
108
109
:::code language="vb" source="~/snippets/visualbasic/api/system.collections.concurrent/concurrentbag/concbag.vb" id="Snippet1":::
109
110
110
111
]]> </format >
You can’t perform that action at this time.
0 commit comments