diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run11.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run11.fs
new file mode 100644
index 00000000000..38c286106e3
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run11.fs
@@ -0,0 +1,17 @@
+module Run11
+//
+open System.Threading
+open System.Threading.Tasks
+
+let showThreadInfo s =
+ printfn $"%s{s} thread ID: {Thread.CurrentThread.ManagedThreadId}"
+
+showThreadInfo "Application"
+
+let t = Task.Run(fun () -> showThreadInfo "Task")
+t.Wait()
+
+// The example displays the following output:
+// Application thread ID: 1
+// Task thread ID: 3
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run28.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run28.fs
new file mode 100644
index 00000000000..40b7a90b171
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run28.fs
@@ -0,0 +1,71 @@
+module Run28
+//
+open System
+open System.Collections.Generic
+open System.Threading
+open System.Threading.Tasks
+
+let source = new CancellationTokenSource()
+let token = source.Token
+let mutable completedIterations = 0
+
+let tasks =
+ [| for _ = 0 to 19 do
+ Task.Run(
+ (fun () ->
+ let mutable iterations = 0
+
+ for _ = 1 to 2000000 do
+ token.ThrowIfCancellationRequested()
+ iterations <- iterations + 1
+
+ Interlocked.Increment &completedIterations |> ignore
+
+ if completedIterations >= 10 then
+ source.Cancel()
+
+ iterations),
+ token
+ ) |]
+
+printfn "Waiting for the first 10 tasks to complete...\n"
+
+try
+ tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
+
+with :? AggregateException ->
+ printfn "Status of tasks:\n"
+ printfn "%10s %20s %14s" "Task Id" "Status" "Iterations"
+
+ for t in tasks do
+ if t.Status <> TaskStatus.Canceled then
+ t.Result.ToString "N0"
+ else
+ "n/a"
+ |> printfn "%10i %20O %14s" t.Id t.Status
+
+// The example displays output like the following:
+// Status of tasks:
+//
+// Task Id Status Iterations
+// 1 RanToCompletion 2,000,000
+// 2 RanToCompletion 2,000,000
+// 3 RanToCompletion 2,000,000
+// 4 RanToCompletion 2,000,000
+// 5 RanToCompletion 2,000,000
+// 6 RanToCompletion 2,000,000
+// 7 RanToCompletion 2,000,000
+// 8 RanToCompletion 2,000,000
+// 9 RanToCompletion 2,000,000
+// 10 RanToCompletion 1,658,326
+// 11 RanToCompletion 1,988,506
+// 12 RanToCompletion 2,000,000
+// 13 RanToCompletion 1,942,246
+// 14 RanToCompletion 950,108
+// 15 RanToCompletion 1,837,832
+// 16 RanToCompletion 1,687,182
+// 17 RanToCompletion 194,548
+// 18 Canceled Not Started
+// 19 Canceled Not Started
+// 20 Canceled Not Started
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run7.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run7.fs
new file mode 100644
index 00000000000..188e39b36bb
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run7.fs
@@ -0,0 +1,74 @@
+module Run7
+//
+open System
+open System.Collections.Generic
+open System.Threading
+open System.Threading.Tasks
+
+let source = new CancellationTokenSource()
+let token = source.Token
+let mutable completedIterations = 0
+
+let tasks =
+ [| for _ = 0 to 19 do
+ Task.Run(
+ (fun () ->
+ let mutable iterations = 0
+
+ for _ = 1 to 2000000 do
+ token.ThrowIfCancellationRequested()
+ iterations <- iterations + 1
+
+ Interlocked.Increment &completedIterations |> ignore
+
+ if completedIterations >= 10 then
+ source.Cancel()
+
+ iterations),
+ token
+ )
+
+ |]
+
+printfn "Waiting for the first 10 tasks to complete...\n"
+
+try
+ tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
+with :? AggregateException ->
+ printfn "Status of tasks:\n"
+ printfn "%10s %20s %14s" "Task Id" "Status" "Iterations"
+
+ for t in tasks do
+ if t.Status <> TaskStatus.Canceled then
+ t.Result.ToString "N0"
+ else
+ "n/a"
+ |> printfn "%10i %20O %14s" t.Id t.Status
+
+
+// The example displays output like the following:
+// Waiting for the first 10 tasks to complete...
+// Status of tasks:
+//
+// Task Id Status Iterations
+// 1 RanToCompletion 2,000,000
+// 2 RanToCompletion 2,000,000
+// 3 RanToCompletion 2,000,000
+// 4 RanToCompletion 2,000,000
+// 5 RanToCompletion 2,000,000
+// 6 RanToCompletion 2,000,000
+// 7 RanToCompletion 2,000,000
+// 8 RanToCompletion 2,000,000
+// 9 RanToCompletion 2,000,000
+// 10 Canceled n/a
+// 11 Canceled n/a
+// 12 Canceled n/a
+// 13 Canceled n/a
+// 14 Canceled n/a
+// 15 Canceled n/a
+// 16 RanToCompletion 2,000,000
+// 17 Canceled n/a
+// 18 Canceled n/a
+// 19 Canceled n/a
+// 20 Canceled n/a
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/ctor1.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/ctor1.fs
new file mode 100644
index 00000000000..6bef9832320
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/ctor1.fs
@@ -0,0 +1,34 @@
+module ctor1
+//
+open System.Collections.Concurrent
+open System.IO
+open System.Threading.Tasks
+
+let main =
+ task {
+ let list = ConcurrentBag()
+ let dirNames = [ "."; ".." ]
+ let tasks = ResizeArray()
+
+ for dirName in dirNames do
+ let t =
+ new Task(fun () ->
+ for path in Directory.GetFiles dirName do
+ list.Add path)
+
+ tasks.Add t
+ t.Start()
+
+ do! tasks.ToArray() |> Task.WhenAll
+
+ for t in tasks do
+ printfn $"Task {t.Id} Status: {t.Status}"
+
+ printfn $"Number of files read: {list.Count}"
+ }
+
+// The example displays output like the following:
+// Task 1 Status: RanToCompletion
+// Task 2 Status: RanToCompletion
+// Number of files read: 23
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/fs.fsproj
new file mode 100644
index 00000000000..3199b411f70
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/fs.fsproj
@@ -0,0 +1,18 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run2.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run2.fs
new file mode 100644
index 00000000000..cedc0f42821
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run2.fs
@@ -0,0 +1,32 @@
+module run2
+// Example for Task.Run(Action) method.
+
+//
+open System.Collections.Concurrent
+open System.IO
+open System.Threading.Tasks
+
+let list = ConcurrentBag()
+let dirNames = [ "."; ".." ]
+let tasks = ResizeArray()
+
+for dirName in dirNames do
+ let t =
+ Task.Run(fun () ->
+ for path in Directory.GetFiles dirName do
+ list.Add path)
+
+ tasks.Add t
+
+tasks.ToArray() |> Task.WaitAll
+
+for t in tasks do
+ printfn $"Task {t.Id} Status: {t.Status}"
+
+printfn $"Number of files read: {list.Count}"
+
+// The example displays output like the following:
+// Task 1 Status: RanToCompletion
+// Task 2 Status: RanToCompletion
+// Number of files read: 23
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run31.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run31.fs
new file mode 100644
index 00000000000..52aa48ebbff
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run31.fs
@@ -0,0 +1,34 @@
+module run31
+//
+open System
+open System.IO
+open System.Text.RegularExpressions
+open System.Threading.Tasks
+
+let pattern = @"\p{P}*\s+"
+let titles = [| "Sister Carrie"; "The Financier" |]
+
+let tasks =
+ Array.map (fun title ->
+ Task.Run(fun () ->
+ // Create filename from title.
+ let fn = title + ".txt"
+
+ if File.Exists fn then
+ use sr = new StreamReader(fn)
+ let input = sr.ReadToEndAsync().Result
+ Regex.Matches(input, pattern).Count
+ else
+ 0)) titles
+
+tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
+
+printfn "Word Counts:\n"
+
+for i = 0 to tasks.Length - 1 do
+ printfn $"%s{titles.[i]}: %10d{tasks.[i].Result} words"
+
+// The example displays the following output:
+// Sister Carrie: 159,374 words
+// The Financier: 196,362 words
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run4.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run4.fs
new file mode 100644
index 00000000000..bd12db48127
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run4.fs
@@ -0,0 +1,59 @@
+module run4
+// Illustrates the Task.Run(Action, CancellationToken) overload.
+
+//
+open System
+open System.IO
+open System.Threading
+open System.Threading.Tasks
+
+let main =
+ task {
+ use tokenSource = new CancellationTokenSource()
+ let token = tokenSource.Token
+ let files = ResizeArray()
+
+ let t =
+ new Task(
+ (fun () ->
+ let dir = @"C:\Windows\System32\"
+ let obj = obj ()
+
+ if Directory.Exists dir then
+ Parallel.ForEach(
+ Directory.GetFiles dir,
+ fun f ->
+ if token.IsCancellationRequested then
+ token.ThrowIfCancellationRequested()
+
+ let fi = FileInfo f
+ lock obj (fun () -> files.Add(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))
+ )
+ |> ignore),
+ token
+ )
+
+ t.Start()
+ tokenSource.Cancel()
+
+ try
+ do! t
+ printfn $"Retrieved information for {files.Count} files."
+
+ with :? AggregateException as e ->
+ printfn "Exception messages:"
+
+ for ie in e.InnerExceptions do
+ printfn $" {ie.GetType().Name}: {ie.Message}"
+
+ printfn $"Task status: {t.Status}"
+ }
+
+main.Wait()
+
+// The example displays the following output:
+// Exception messages:
+// TaskCanceledException: A task was canceled.
+//
+// Task status: Canceled
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run41.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run41.fs
new file mode 100644
index 00000000000..b247761367d
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run41.fs
@@ -0,0 +1,62 @@
+module run41
+// Illustrates the Task.Run(Action, CancellationToken) overload.
+
+//
+open System
+open System.IO
+open System.Threading
+open System.Threading.Tasks
+
+let main =
+ task {
+ use tokenSource = new CancellationTokenSource()
+ let token = tokenSource.Token
+ let files = ResizeArray()
+
+ let t =
+ Task.Run(
+ (fun () ->
+ let dir = "C:\\Windows\\System32\\"
+ let obj = obj ()
+
+ if Directory.Exists dir then
+ Parallel.ForEach(
+ Directory.GetFiles dir,
+ (fun f ->
+ if token.IsCancellationRequested then
+ token.ThrowIfCancellationRequested()
+
+ let fi = FileInfo f
+ lock obj (fun () -> files.Add(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc)))
+ )
+ |> ignore),
+ token
+ )
+
+ do! Task.Yield()
+ tokenSource.Cancel()
+
+ try
+ do! t
+ printfn $"Retrieved information for {files.Count} files."
+
+ with :? AggregateException as e ->
+ printfn "Exception messages:"
+
+ for ie in e.InnerExceptions do
+ printfn $" {ie.GetType().Name}: {ie.Message}"
+
+ printfn $"Task status: {t.Status}"
+ }
+
+main.Wait()
+
+
+// The example displays the following output:
+// Exception messages:
+// TaskCanceledException: A task was canceled.
+// TaskCanceledException: A task was canceled.
+// ...
+//
+// Task status: Canceled
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run6.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run6.fs
new file mode 100644
index 00000000000..348ec2a2cc3
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run6.fs
@@ -0,0 +1,13 @@
+module run6
+//
+open System.Threading
+open System.Threading.Tasks
+
+printfn $"Application thread ID: {Thread.CurrentThread.ManagedThreadId}"
+let t = Task.Run(fun () -> printfn $"Task thread ID: {Thread.CurrentThread.ManagedThreadId}")
+t.Wait()
+
+// The example displays the following output:
+// Application thread ID: 1
+// Task thread ID: 3
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/.ctor/startnew3.fs b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/startnew3.fs
new file mode 100644
index 00000000000..d6c847d6730
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/.ctor/startnew3.fs
@@ -0,0 +1,55 @@
+module startnew3
+//
+open System
+open System.Threading.Tasks
+
+let main =
+ task {
+ let tasks = ResizeArray()
+ let rnd = Random()
+ let lockObj = obj ()
+
+ let words6 =
+ [ "reason"
+ "editor"
+ "rioter"
+ "rental"
+ "senior"
+ "regain"
+ "ordain"
+ "rained" ]
+
+ for word6 in words6 do
+ let t =
+ new Task(
+ (fun word ->
+ let chars = (string word).ToCharArray()
+ let order = Array.zeroCreate chars.Length
+
+ lock lockObj (fun () ->
+ for i = 0 to order.Length - 1 do
+ order[i] <- rnd.NextDouble())
+
+ Array.Sort(order, chars)
+ printfn $"{word} --> {new String(chars)}"),
+ word6
+ )
+
+ t.Start()
+ tasks.Add t
+
+ do! tasks.ToArray() |> Task.WhenAll
+ }
+
+main.Wait()
+
+// The example displays output like the following:
+// regain --> irnaeg
+// ordain --> rioadn
+// reason --> soearn
+// rained --> rinade
+// rioter --> itrore
+// senior --> norise
+// rental --> atnerl
+// editor --> oteird
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/continuewith1.fs b/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/continuewith1.fs
new file mode 100644
index 00000000000..f8f567a42c8
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/continuewith1.fs
@@ -0,0 +1,47 @@
+module continuewith1
+//
+open System
+open System.Threading.Tasks
+
+let firstTask =
+ Task.Factory.StartNew(fun () ->
+ let rnd = Random()
+ let dates = Array.zeroCreate 100
+ let buffer = Array.zeroCreate 8
+ let mutable i = dates.GetLowerBound 0
+
+ while i <= dates.GetUpperBound 0 do
+ rnd.NextBytes buffer
+ let ticks = BitConverter.ToInt64(buffer, 0)
+
+ if ticks > DateTime.MinValue.Ticks && ticks < DateTime.MaxValue.Ticks then
+ dates[i] <- DateTime ticks
+ i <- i + 1
+
+ dates)
+
+let continuationTask =
+ firstTask.ContinueWith(
+ Action>(fun antecedent ->
+ let dates: DateTime[] = antecedent.Result
+ let mutable earliest = dates[0]
+ let mutable latest = earliest
+
+ for i = dates.GetLowerBound 0 + 1 to dates.GetUpperBound 0 do
+ if dates.[i] < earliest then
+ earliest <- dates.[i]
+
+ if dates.[i] > latest then
+ latest <- dates.[i]
+
+ printfn $"Earliest date: {earliest}"
+ printfn $"Latest date: {latest}")
+ )
+// Since a console application otherwise terminates, wait for the continuation to complete.
+continuationTask.Wait()
+
+
+// The example displays output like the following:
+// Earliest date: 2/11/0110 12:03:41 PM
+// Latest date: 7/29/9989 2:14:49 PM
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/fs.fsproj
new file mode 100644
index 00000000000..5ca4429f3f4
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/fs.fsproj
@@ -0,0 +1,10 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay1.fs
new file mode 100644
index 00000000000..ac12b805f83
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay1.fs
@@ -0,0 +1,17 @@
+module delay1
+//
+open System.Threading.Tasks
+
+let t =
+ Task.Run(fun () ->
+ task {
+ do! Task.Delay 1000
+ return 42
+ })
+
+t.Wait()
+printfn $"Task t Status: {t.Status}, Result: {t.Result}"
+
+// The example displays the following output:
+// Task t Status: RanToCompletion, Result: 42
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay2.fs b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay2.fs
new file mode 100644
index 00000000000..3ba71b7f8b5
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay2.fs
@@ -0,0 +1,18 @@
+module delay2
+//
+open System
+open System.Threading.Tasks
+
+let t =
+ Task.Run(fun () ->
+ task {
+ do! Task.Delay(TimeSpan.FromSeconds 1.5)
+ return 42
+ })
+
+t.Wait()
+printfn $"Task t Status: {t.Status}, Result: {t.Result}"
+
+// The example displays the following output:
+// Task t Status: RanToCompletion, Result: 42
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay3.fs b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay3.fs
new file mode 100644
index 00000000000..c50ee2254b5
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay3.fs
@@ -0,0 +1,36 @@
+module delay3
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+let source = new CancellationTokenSource()
+
+let t =
+ Task.Run(fun () ->
+ task {
+ do! Task.Delay(1000, source.Token)
+ return 42
+ })
+
+source.Cancel()
+
+try
+ t.Wait()
+
+with :? AggregateException as ae ->
+ for e in ae.InnerExceptions do
+ printfn $"{e.GetType().Name}: {e.Message}"
+
+printf $"Task t Status: {t.Status}"
+
+if t.Status = TaskStatus.RanToCompletion then
+ printf $", Result: {t.Result}"
+
+source.Dispose()
+
+
+// The example displays the following output:
+// TaskCanceledException: A task was canceled.
+// Task t Status: Canceled
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay4.fs b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay4.fs
new file mode 100644
index 00000000000..91dc791c20f
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay4.fs
@@ -0,0 +1,36 @@
+module delay4
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+let source = new CancellationTokenSource()
+
+let t =
+ Task.Run(fun () ->
+ task {
+
+ do! Task.Delay(TimeSpan.FromSeconds(1.5), source.Token)
+ return 42
+ })
+
+source.Cancel()
+
+try
+ t.Wait()
+
+with :? AggregateException as ae ->
+ for e in ae.InnerExceptions do
+ printfn $"{e.GetType().Name}: {e.Message}"
+
+printf $"Task t Status: {t.Status}"
+
+if t.Status = TaskStatus.RanToCompletion then
+ printf $", Result: {t.Result}"
+
+source.Dispose()
+
+// The example displays output like the following:
+// TaskCanceledException: A task was canceled.
+// Task t Status: Canceled
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay5.fs b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay5.fs
new file mode 100644
index 00000000000..31ac0778d23
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay5.fs
@@ -0,0 +1,59 @@
+module delay5
+
+open System.Diagnostics
+open System.Threading.Tasks
+
+let delayAtStart () =
+ //
+ let sw = Stopwatch.StartNew()
+
+ let delay =
+ Task
+ .Delay(1000)
+ .ContinueWith(fun _ ->
+ sw.Stop()
+ sw.ElapsedMilliseconds)
+
+ printfn $"Elapsed milliseconds: {delay.Result}"
+// The example displays output like the following:
+// Elapsed milliseconds: 1013
+//
+
+
+let delayDuring () =
+ //
+ let delay =
+ Task.Run(fun () ->
+ let sw = Stopwatch.StartNew()
+ Task.Delay(2000).Wait()
+ sw.Stop()
+ sw.ElapsedMilliseconds)
+
+ printfn $"Elapsed milliseconds: {delay.Result}"
+// The example displays output like the following:
+// Elapsed milliseconds: 2006
+//
+
+
+let delayDuringLang () =
+ //
+ let delay =
+ Task.Run(fun () ->
+ task {
+ let sw = Stopwatch.StartNew()
+ do! Task.Delay 2500
+ sw.Stop()
+ return sw.ElapsedMilliseconds
+ })
+
+ printfn $"Elapsed milliseconds: {delay.Result}"
+// The example displays output like the following:
+// Elapsed milliseconds: 2501
+//
+
+
+delayAtStart ()
+printfn "---"
+delayDuring ()
+printfn "---"
+delayDuringLang ()
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Delay/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/Delay/fs.fsproj
new file mode 100644
index 00000000000..dcdbd923589
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Delay/fs.fsproj
@@ -0,0 +1,14 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Factory/factory1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Factory/factory1.fs
new file mode 100644
index 00000000000..e5528762a9f
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Factory/factory1.fs
@@ -0,0 +1,28 @@
+module factory1
+//
+open System
+open System.IO
+open System.Threading.Tasks
+
+let mutable files = Unchecked.defaultof
+let mutable dirs = Unchecked.defaultof
+let docsDirectory = Environment.GetFolderPath Environment.SpecialFolder.MyDocuments
+
+let tasks =
+ [| Task.Factory.StartNew(fun () -> files <- Directory.GetFiles docsDirectory)
+ Task.Factory.StartNew(fun () -> dirs <- Directory.GetDirectories docsDirectory) |]
+
+Task.Factory.ContinueWhenAll(
+ tasks,
+ fun completedTasks ->
+ printfn $"{docsDirectory} contains: "
+ printfn $" {dirs.Length} subdirectories"
+ printfn $" {files.Length} files"
+)
+|> ignore
+
+// The example displays output like the following:
+// C:\Users\\Documents contains:
+// 24 subdirectories
+// 16 files
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Factory/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/Factory/fs.fsproj
new file mode 100644
index 00000000000..fc2e4d38edd
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Factory/fs.fsproj
@@ -0,0 +1,10 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.fs b/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.fs
new file mode 100644
index 00000000000..c38e5cdf930
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.fs
@@ -0,0 +1,60 @@
+module fromresult1
+//
+open System
+open System.IO
+open System.Threading
+open System.Threading.Tasks
+
+let getFileLengthsAsync filePath =
+ if Directory.Exists filePath |> not then
+ DirectoryNotFoundException "Invalid directory name."
+ |> Task.FromException
+
+ else
+ let files = Directory.GetFiles filePath
+
+ if files.Length = 0 then
+ Task.FromResult 0L
+ else
+ Task.Run(fun () ->
+ let mutable total = 0L
+
+ Parallel.ForEach(
+ files,
+ fun fileName ->
+ use fs =
+ new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 256, true)
+
+ Interlocked.Add(ref total, fs.Length) |> ignore
+ )
+ |> ignore
+
+ total)
+
+let args = Environment.GetCommandLineArgs()[1..]
+
+if args.Length > 0 then
+ let tasks = Array.map getFileLengthsAsync args
+
+ try
+ Seq.cast tasks |> Seq.toArray |> Task.WaitAll
+
+ // Ignore exceptions here.
+ with :? AggregateException ->
+ ()
+
+ for i = 0 to tasks.Length - 1 do
+ if tasks[i].Status = TaskStatus.Faulted then
+ printfn $"{args[i + 1]} does not exist"
+ else
+ printfn $"{tasks[i].Result:N0} bytes in files in '{args[i + 1]}'"
+else
+ printfn "Syntax error: Include one or more file paths."
+
+// When launched with the following command line arguments:
+// subdir . newsubdir
+// the example displays output like the following:
+// 0 bytes in files in 'subdir'
+// 2,059 bytes in files in '.'
+// newsubdir does not exist
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fs.fsproj
new file mode 100644
index 00000000000..81e68858e0e
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fs.fsproj
@@ -0,0 +1,10 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait1.fs
new file mode 100644
index 00000000000..82303ddd264
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait1.fs
@@ -0,0 +1,22 @@
+module Wait1
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+let rand = Random()
+
+// Wait on a single task with no timeout specified.
+let taskA = Task.Run(fun () -> Thread.Sleep 2000)
+printfn $"taskA Status: {taskA.Status}"
+try
+ taskA.Wait()
+ printfn $"taskA Status: {taskA.Status}"
+
+with :? AggregateException ->
+ printfn "Exception in taskA."
+
+// The example displays output like the following:
+// taskA Status: WaitingToRun
+// taskA Status: RanToCompletion
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait2.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait2.fs
new file mode 100644
index 00000000000..72bbb825d56
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait2.fs
@@ -0,0 +1,25 @@
+module Wait2
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+// Wait on a single task with a timeout specified.
+let taskA = Task.Run(fun () -> Thread.Sleep 2000)
+
+try
+ taskA.Wait 1000 |> ignore // Wait for 1 second.
+ let completed = taskA.IsCompleted
+ printfn $"Task A completed: {completed}, Status: {taskA.Status}"
+
+ if not completed then
+ printfn "Timed out before task A completed."
+
+with :? AggregateException ->
+ printfn "Exception in taskA."
+
+
+// The example displays output like the following:
+// Task A completed: False, Status: Running
+// Timed out before task A completed.
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll1.fs
new file mode 100644
index 00000000000..3f0e0c0c056
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll1.fs
@@ -0,0 +1,38 @@
+module WaitAll1
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+// Wait for all tasks to complete.
+let tasks =
+ [| for _ = 0 to 9 do
+ Task.Run(fun () -> Thread.Sleep 2000) |]
+
+try
+ Task.WaitAll tasks
+
+with :? AggregateException as ae ->
+ printfn "One or more exceptions occurred: "
+
+ for ex in ae.Flatten().InnerExceptions do
+ printfn $" {ex.Message}"
+
+printfn "Status of completed tasks:"
+
+for t in tasks do
+ printfn $" Task #{t.Id}: {t.Status}"
+
+// The example displays the following output:
+// Status of completed tasks:
+// Task #2: RanToCompletion
+// Task #1: RanToCompletion
+// Task #3: RanToCompletion
+// Task #4: RanToCompletion
+// Task #6: RanToCompletion
+// Task #5: RanToCompletion
+// Task #7: RanToCompletion
+// Task #8: RanToCompletion
+// Task #9: RanToCompletion
+// Task #10: RanToCompletion
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll2.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll2.fs
new file mode 100644
index 00000000000..9d466754397
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll2.fs
@@ -0,0 +1,86 @@
+module WaitAll2
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+// Create a cancellation token and cancel it.
+let source1 = new CancellationTokenSource()
+let token1 = source1.Token
+source1.Cancel()
+// Create a cancellation token for later cancellation.
+let source2 = new CancellationTokenSource()
+let token2 = source2.Token
+
+// Create a series of tasks that will complete, be cancelled,
+// timeout, or throw an exception.
+let tasks =
+ [| for i in 0..11 do
+ match i % 4 with
+ // Task should run to completion.
+ | 0 -> Task.Run(fun () -> Thread.Sleep 2000)
+ // Task should be set to canceled state.
+ | 1 -> Task.Run(fun () -> Thread.Sleep 2000, token1)
+ // Task should throw an exception.
+ | 2 -> Task.Run(fun () -> NotSupportedException())
+ // Task should examine cancellation token.
+ | _ ->
+ Task.Run(fun () ->
+ Thread.Sleep 2000
+
+ if token2.IsCancellationRequested then
+ token2.ThrowIfCancellationRequested()
+
+ Thread.Sleep 500, token2) |]
+
+
+Thread.Sleep 250
+source2.Cancel()
+
+try
+ Task.WaitAll tasks
+
+with :? AggregateException as ae ->
+ printfn "One or more exceptions occurred:"
+
+ for ex in ae.InnerExceptions do
+ printfn $" {ex.GetType().Name}: {ex.Message}"
+
+printfn "\nStatus of tasks:"
+
+for t in tasks do
+ printfn $" Task #{t.Id}: {t.Status}"
+
+ if isNull t.Exception |> not then
+ for ex in t.Exception.InnerExceptions do
+ printfn $" {ex.GetType().Name}: {ex.Message}"
+
+// The example displays output like the following:
+// One or more exceptions occurred:
+// TaskCanceledException: A task was canceled.
+// NotSupportedException: Specified method is not supported.
+// TaskCanceledException: A task was canceled.
+// TaskCanceledException: A task was canceled.
+// NotSupportedException: Specified method is not supported.
+// TaskCanceledException: A task was canceled.
+// TaskCanceledException: A task was canceled.
+// NotSupportedException: Specified method is not supported.
+// TaskCanceledException: A task was canceled.
+//
+// Status of tasks:
+// Task #13: RanToCompletion
+// Task #1: Canceled
+// Task #3: Faulted
+// NotSupportedException: Specified method is not supported.
+// Task #8: Canceled
+// Task #14: RanToCompletion
+// Task #4: Canceled
+// Task #6: Faulted
+// NotSupportedException: Specified method is not supported.
+// Task #7: Canceled
+// Task #15: RanToCompletion
+// Task #9: Canceled
+// Task #11: Faulted
+// NotSupportedException: Specified method is not supported.
+// Task #12: Canceled
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/WhenAny1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/WhenAny1.fs
new file mode 100644
index 00000000000..0909a2ca968
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/WhenAny1.fs
@@ -0,0 +1,81 @@
+module WhenAny1
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+let rnd = new Random()
+
+let tasks =
+ [| for _ = 0 to 2 do
+ Task.Run(fun () -> rnd.Next(500, 3000) |> Thread.Sleep) |]
+
+try
+ let index = Task.WaitAny tasks
+ printfn $"Task #{tasks[index].Id} completed first.\n"
+ printfn "Status of all tasks:"
+
+ for t in tasks do
+ printfn $" Task #{t.Id}: {t.Status}"
+
+with :? AggregateException ->
+ printfn "An exception occurred."
+
+// The example displays output like the following:
+// Task #1 completed first.
+//
+// Status of all tasks:
+// Task #3: Running
+// Task #1: RanToCompletion
+// Task #4: Running
+//
+
+
+
+
+// // Wait for first task to complete.
+// Task[] tasks2 = new Task[3];
+//
+// // Try three different approaches to the problem. Take the first one.
+// tasks2[0] = Task.Factory.StartNew(() => TrySolution1());
+// tasks2[1] = Task.Factory.StartNew(() => TrySolution2());
+// tasks2[2] = Task.Factory.StartNew(() => TrySolution3());
+//
+//
+// int index = Task.WaitAny(tasks2);
+// double d = tasks2[index].Result;
+// Console.WriteLine("task[{0}] completed first with result of {1}.", index, d);
+//
+// Console.ReadKey();
+//
+//
+//
+// static void DoSomeWork(int val)
+//
+// // Pretend to do something.
+// Thread.SpinWait(val);
+//
+//
+// static double TrySolution1()
+//
+// int i = rand.Next(1000000);
+// // Simulate work by spinning
+// Thread.SpinWait(i);
+// return DateTime.Now.Millisecond;
+//
+// static double TrySolution2()
+//
+// int i = rand.Next(1000000);
+// // Simulate work by spinning
+// Thread.SpinWait(i);
+// return DateTime.Now.Millisecond;
+//
+// static double TrySolution3()
+//
+// int i = rand.Next(1000000);
+// // Simulate work by spinning
+// Thread.SpinWait(i);
+// Thread.SpinWait(1000000);
+// return DateTime.Now.Millisecond;
+//
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationoptions.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationoptions.fs
new file mode 100644
index 00000000000..ed00b597947
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationoptions.fs
@@ -0,0 +1,83 @@
+module continuationoptions
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+// Demonstrated features:
+// TaskContinuationOptions
+// Task.ContinueWith()
+// Task.Factory
+// Task.Wait()
+// Expected results:
+// This sample demonstrates branched continuation sequences - Task+Commit or Task+Rollback.
+// Notice that no if statements are used.
+// The first sequence is successful - tran1 and commitTran1 are executed. rollbackTran1 is canceled.
+// The second sequence is unsuccessful - tran2 and rollbackTran2 are executed. tran2 is faulted, and commitTran2 is canceled.
+// Documentation:
+// http://msdn.microsoft.com/library/system.threading.tasks.taskcontinuationoptions(VS.100).aspx
+let success =
+ fun () ->
+ printfn $"Task={Task.CurrentId}, Thread={Thread.CurrentThread.ManagedThreadId}: Begin successful transaction"
+
+let failure =
+ fun () ->
+
+ printfn
+ $"Task={Task.CurrentId}, Thread={Thread.CurrentThread.ManagedThreadId}: Begin transaction and encounter an error"
+
+ raise (InvalidOperationException "SIMULATED EXCEPTION")
+
+let commit =
+ fun antecendent ->
+ printfn $"Task={Task.CurrentId}, Thread={Thread.CurrentThread.ManagedThreadId}: Commit transaction"
+
+let rollback =
+ fun (antecendent: Task) ->
+
+ // "Observe" your antecedent's exception so as to avoid an exception
+ // being thrown on the finalizer thread
+ let unused = antecendent.Exception
+
+ printfn $"Task={Task.CurrentId}, Thread={Thread.CurrentThread.ManagedThreadId}: Rollback transaction"
+
+// Successful transaction - Begin + Commit
+printfn "Demonstrating a successful transaction"
+
+// Initial task
+// Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
+let tran1 = Task.Factory.StartNew success
+
+// The following task gets scheduled only if tran1 completes successfully
+let commitTran1 =
+ tran1.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion)
+
+// The following task gets scheduled only if tran1 DOES NOT complete successfully
+let rollbackTran1 =
+ tran1.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion)
+
+// For demo purposes, wait for the sample to complete
+commitTran1.Wait()
+
+// -----------------------------------------------------------------------------------
+
+// Failed transaction - Begin + exception + Rollback
+printfn "\nDemonstrating a failed transaction"
+
+// Initial task
+// Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
+let tran2: Task = Task.Factory.StartNew failure
+
+// The following task gets scheduled only if tran2 completes successfully
+let commitTran2 =
+ tran2.ContinueWith(Action commit, TaskContinuationOptions.OnlyOnRanToCompletion)
+
+// The following task gets scheduled only if tran2 DOES NOT complete successfully
+let rollbackTran2 =
+ tran2.ContinueWith(Action rollback, TaskContinuationOptions.NotOnRanToCompletion)
+
+// For demo purposes, wait for the sample to complete
+rollbackTran2.Wait()
+
+
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationsimple.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationsimple.fs
new file mode 100644
index 00000000000..039d27b7629
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationsimple.fs
@@ -0,0 +1,54 @@
+module continuationsimple
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+// Demonstrated features:
+// Task.Factory
+// Task.ContinueWith()
+// Task.Wait()
+// Expected results:
+// A sequence of three unrelated tasks is created and executed in this order - alpha, beta, gamma.
+// A sequence of three related tasks is created - each task negates its argument and passes is to the next task: 5, -5, 5 is printed.
+// A sequence of three unrelated tasks is created where tasks have different types.
+// Documentation:
+// http://msdn.microsoft.com/library/system.threading.tasks.taskfactory_members(VS.100).aspx
+let action =
+ fun str -> printfn $"Task={Task.CurrentId}, str=%s{str}, Thread={Thread.CurrentThread.ManagedThreadId}"
+
+// Creating a sequence of action tasks (that return no result).
+printfn "Creating a sequence of action tasks (that return no result)"
+
+Task
+ .Factory
+ .StartNew(fun () -> action "alpha")
+ .ContinueWith(fun antecendent -> action "beta") // Antecedent data is ignored
+ .ContinueWith(fun antecendent -> action "gamma")
+ .Wait()
+
+let negate =
+ fun n ->
+ printfn $"Task={Task.CurrentId}, n={n}, -n={2 - n}, Thread={Thread.CurrentThread.ManagedThreadId}"
+ -n
+
+// Creating a sequence of function tasks where each continuation uses the result from its antecendent
+printfn "\nCreating a sequence of function tasks where each continuation uses the result from its antecendent"
+
+Task
+ .Factory.StartNew(fun () -> negate 5)
+ .ContinueWith(Func, int>(fun antecedent -> negate antecedent.Result)) // Antecedent result feeds into continuation
+ .ContinueWith(Func, int>(fun antecedent -> negate antecedent.Result))
+ .Wait()
+
+// Creating a sequence of tasks where you can mix and match the types
+printfn "\nCreating a sequence of tasks where you can mix and match the types"
+
+Task
+ .Factory.StartNew(fun () -> negate 6)
+ .ContinueWith(Action(fun antecendent -> action "x"))
+ .ContinueWith(fun antecendent -> negate 7)
+ .Wait()
+
+
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/Overview/fs.fsproj
new file mode 100644
index 00000000000..94873285fa2
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/fs.fsproj
@@ -0,0 +1,20 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/run1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/run1.fs
new file mode 100644
index 00000000000..1e986c10583
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/run1.fs
@@ -0,0 +1,17 @@
+module run1
+//
+open System.Threading.Tasks
+
+let main =
+ task {
+ do!
+ Task.Run(fun () ->
+ for i = 0 to 1000000 do
+ printfn $"Finished {i} loop iterations")
+ }
+
+main.Wait()
+
+// The example displays the following output:
+// Finished 1000001 loop iterations
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew.fs
new file mode 100644
index 00000000000..3c6d07303c0
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew.fs
@@ -0,0 +1,46 @@
+module startnew
+//
+open System.Threading
+open System.Threading.Tasks
+
+let action =
+ fun (obj: obj) -> printfn $"Task={Task.CurrentId}, obj={obj}, Thread={Thread.CurrentThread.ManagedThreadId}"
+
+// Create a task but do not start it.
+let t1 = new Task(action, "alpha")
+
+// Construct a started task
+let t2 = Task.Factory.StartNew(action, "beta")
+// Block the main thread to demonstrate that t2 is executing
+t2.Wait()
+
+// Launch t1
+t1.Start()
+printfn $"t1 has been launched. (Main Thread={Thread.CurrentThread.ManagedThreadId})"
+// Wait for the task to finish.
+t1.Wait()
+
+// Construct a started task using Task.Run.
+let taskData = "delta"
+
+let t3 =
+ Task.Run(fun () -> printfn $"Task={Task.CurrentId}, obj={taskData}, Thread={Thread.CurrentThread.ManagedThreadId}")
+// Wait for the task to finish.
+t3.Wait()
+
+// Construct an unstarted task
+let t4 = new Task(action, "gamma")
+// Run it synchronously
+t4.RunSynchronously()
+// Although the task was run synchronously, it is a good practice
+// to wait for it in the event exceptions were thrown by the task.
+t4.Wait()
+
+
+// The example displays output like the following:
+// Task=1, obj=beta, Thread=3
+// t1 has been launched. (Main Thread=1)
+// Task=2, obj=alpha, Thread=4
+// Task=3, obj=delta, Thread=3
+// Task=4, obj=gamma, Thread=1
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew1.fs
new file mode 100644
index 00000000000..a66aff79a9d
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew1.fs
@@ -0,0 +1,16 @@
+module startnew1
+//
+open System.Threading.Tasks
+
+let t =
+ Task.Factory.StartNew(fun () ->
+ // Just loop.
+ for i = 0 to 1000000 do
+ printfn $"Finished {i} loop iterations")
+
+t.Wait()
+
+
+// The example displays the following output:
+// Finished 1000001 loop iterations
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Overview/waitall.fs b/snippets/fsharp/System.Threading.Tasks/Task/Overview/waitall.fs
new file mode 100644
index 00000000000..2337596ae41
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Overview/waitall.fs
@@ -0,0 +1,76 @@
+module waitall
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+// Define a delegate that prints and returns the system tick count
+let action =
+ fun (obj: obj) ->
+ let i = obj :?> int
+
+ // Make each thread sleep a different time in order to return a different tick count
+ Thread.Sleep(i * 100)
+
+ // The tasks that receive an argument between 2 and 5 throw exceptions
+ if 2 <= i && i <= 5 then
+ raise (InvalidOperationException "SIMULATED EXCEPTION")
+
+
+ let tickCount = Environment.TickCount
+ printfn $"Task={Task.CurrentId}, i={i}, TickCount={tickCount}, Thread={Thread.CurrentThread.ManagedThreadId}"
+ tickCount
+
+// Construct started tasks
+let tasks =
+ [| for i = 0 to 9 do
+ Task.Factory.StartNew (action, i) |]
+
+try
+
+ // Wait for all the tasks to finish.
+ Seq.cast tasks |> Seq.toArray |> Task.WaitAll
+
+ // We should never get to this point
+ printfn "WaitAll() has not thrown exceptions. THIS WAS NOT EXPECTED."
+
+with :? AggregateException as e ->
+ printfn "\nThe following exceptions have been thrown by WaitAll(): (THIS WAS EXPECTED)"
+
+ for ex in e.InnerExceptions do
+ printfn $"\n-------------------------------------------------\n{ex}"
+
+// The example displays output like the following:
+// Task=1, i=0, TickCount=1203822250, Thread=3
+// Task=2, i=1, TickCount=1203822359, Thread=4
+// Task=7, i=6, TickCount=1203823484, Thread=3
+// Task=8, i=7, TickCount=1203823890, Thread=4
+// Task=9, i=8, TickCount=1203824296, Thread=3
+// Task=10, i=9, TickCount=1203824796, Thread=4
+//
+// The following exceptions have been thrown by WaitAll(): (THIS WAS EXPECTED)
+//
+// -------------------------------------------------
+// System.InvalidOperationException: SIMULATED EXCEPTION
+// at Example.b__0(Object obj)
+// at System.Threading.Tasks.Task`1.InnerInvoke()
+// at System.Threading.Tasks.Task.Execute()
+//
+// -------------------------------------------------
+// System.InvalidOperationException: SIMULATED EXCEPTION
+// at Example.b__0(Object obj)
+// at System.Threading.Tasks.Task`1.InnerInvoke()
+// at System.Threading.Tasks.Task.Execute()
+//
+// -------------------------------------------------
+// System.InvalidOperationException: SIMULATED EXCEPTION
+// at Example.b__0(Object obj)
+// at System.Threading.Tasks.Task`1.InnerInvoke()
+// at System.Threading.Tasks.Task.Execute()
+//
+// -------------------------------------------------
+// System.InvalidOperationException: SIMULATED EXCEPTION
+// at Example.b__0(Object obj)
+// at System.Threading.Tasks.Task`1.InnerInvoke()
+// at System.Threading.Tasks.Task.Execute()
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/fs.fsproj
new file mode 100644
index 00000000000..d04f581623d
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/fs.fsproj
@@ -0,0 +1,10 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/runsynchronously1.fs b/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/runsynchronously1.fs
new file mode 100644
index 00000000000..01907b0985f
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/runsynchronously1.fs
@@ -0,0 +1,42 @@
+module runsynchronously1
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+printfn $"Application executing on thread {Thread.CurrentThread.ManagedThreadId}"
+
+let asyncTask =
+ Task.Run(fun () ->
+ printfn $"Task {Task.CurrentId} (asyncTask) executing on Thread {Thread.CurrentThread.ManagedThreadId}"
+ let mutable sum = 0L
+
+ for i = 1 to 1000000 do
+ sum <- sum + int64 i
+
+ sum)
+
+let syncTask =
+ new Task(fun () ->
+ printfn $"Task {Task.CurrentId} (syncTask) executing on Thread {Thread.CurrentThread.ManagedThreadId}"
+ let mutable sum = 0L
+
+ for i = 1 to 1000000 do
+ sum <- sum + int64 i
+
+ sum)
+
+syncTask.RunSynchronously()
+printfn $"\nTask {syncTask.Id} returned {syncTask.Result:N0}"
+printfn $"Task {asyncTask.Id} returned {asyncTask.Result:N0}"
+
+// The example displays the following output:
+// Application executing on thread 1
+// Task 1 (syncTask) executing on Thread 1
+// Task 2 (asyncTask) executing on Thread 3
+// 1 status: RanToCompletion
+// 2 status: RanToCompletion
+//
+// Task 2 returned 500,000,500,000
+// Task 1 returned 500,000,500,000
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Start/Start1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Start/Start1.fs
new file mode 100644
index 00000000000..f64ede22d8c
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Start/Start1.fs
@@ -0,0 +1,28 @@
+module Start1
+//
+open System.Threading
+open System.Threading.Tasks
+
+let t =
+ new Task(fun () ->
+ printfn $"Task {Task.CurrentId} running on thread {Thread.CurrentThread.ManagedThreadId}"
+
+ for i = 1 to 10 do
+ printfn $" Iteration {i}")
+
+t.Start()
+t.Wait() |> ignore
+
+// The example displays output like the following:
+// Task 1 running on thread 3
+// Iteration 1
+// Iteration 2
+// Iteration 3
+// Iteration 4
+// Iteration 5
+// Iteration 6
+// Iteration 7
+// Iteration 8
+// Iteration 9
+// Iteration 10
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Start/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/Start/fs.fsproj
new file mode 100644
index 00000000000..667aa8caccb
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Start/fs.fsproj
@@ -0,0 +1,10 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait5.fs b/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait5.fs
new file mode 100644
index 00000000000..41c4d237ef0
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait5.fs
@@ -0,0 +1,29 @@
+module Wait5
+//
+open System
+open System.Threading.Tasks
+
+let t =
+ Task.Run(fun () ->
+ let rnd = Random()
+ let mutable sum = 0L
+ let n = 5000000
+
+ for _ = 1 to n do
+ let number = rnd.Next(0, 101)
+ sum <- sum + int64 number
+
+ printfn $"Total: {sum:N0}"
+ printfn $"Mean: {float sum / float n:N2}"
+ printfn $"N: {n:N0}")
+
+if t.Wait 150 |> not then
+ printfn "The timeout interval elapsed."
+
+// The example displays output similar to the following:
+// Total: 50,015,714
+// Mean: 50.02
+// N: 1,000,000
+// Or it displays the following output:
+// The timeout interval elapsed.
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait6.fs b/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait6.fs
new file mode 100644
index 00000000000..f27fd352f87
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait6.fs
@@ -0,0 +1,31 @@
+module Wait6
+//
+open System
+open System.Threading.Tasks
+
+let t =
+ Task.Run(fun () ->
+ let rnd = Random()
+ let mutable sum = 0L
+ let n = 5000000
+
+ for _ = 1 to n do
+ let number = rnd.Next(0, 101)
+ sum <- sum + int64 number
+
+ printfn $"Total: {sum:N0}"
+ printfn $"Mean: {float sum / float n:N2}"
+ printfn $"N: {n:N0}")
+
+let ts = TimeSpan.FromMilliseconds 150
+
+if t.Wait ts |> not then
+ printfn "The timeout interval elapsed."
+
+// The example displays output similar to the following:
+// Total: 50,015,714
+// Mean: 50.02
+// N: 1,000,000
+// Or it displays the following output:
+// The timeout interval elapsed.
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Wait/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/Wait/fs.fsproj
new file mode 100644
index 00000000000..6ba91594fb8
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Wait/fs.fsproj
@@ -0,0 +1,14 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait1.fs b/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait1.fs
new file mode 100644
index 00000000000..cb95680e6dd
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait1.fs
@@ -0,0 +1,26 @@
+module wait1
+//
+open System
+open System.Threading.Tasks
+
+let t =
+ Task.Run(fun () ->
+ let rnd = Random()
+ let mutable sum = 0L
+ let n = 1000000
+
+ for _ = 1 to n do
+ let number = rnd.Next(0, 101)
+ sum <- sum + int64 number
+
+ printfn $"Total: {sum:N0}"
+ printfn $"Mean: {float sum / float n:N2}"
+ printfn $"N: {n:N0}")
+
+t.Wait()
+
+// The example displays output similar to the following:
+// Total: 50,015,714
+// Mean: 50.02
+// N: 1,000,000
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait3.fs b/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait3.fs
new file mode 100644
index 00000000000..0abe1daa8c5
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait3.fs
@@ -0,0 +1,34 @@
+module wait3
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+let ts = new CancellationTokenSource()
+
+let t =
+ Task.Run(fun () ->
+ printfn "Calling Cancel..."
+ ts.Cancel()
+ Task.Delay(5000).Wait()
+ printfn $"Task ended delay...")
+
+try
+ printfn "About to wait for the task to complete..."
+ t.Wait ts.Token
+
+with :? OperationCanceledException as e ->
+ printfn $"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
+ Thread.Sleep 6000
+ printfn $"After sleeping, the task status: {t.Status:G}"
+
+ts.Dispose()
+
+
+// The example displays output like the following:
+// About to wait for the task to complete...
+// Calling Cancel...
+// OperationCanceledException: The wait has been canceled. Task status: Running
+// Task ended delay...
+// After sleeping, the task status: RanToCompletion
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait4.fs b/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait4.fs
new file mode 100644
index 00000000000..66060313034
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait4.fs
@@ -0,0 +1,49 @@
+module wait4
+//
+open System
+open System.Threading
+open System.Threading.Tasks
+
+let cancelToken (obj: obj) =
+ Thread.Sleep 1500
+ printfn $"Canceling the cancellation token from thread {Thread.CurrentThread.ManagedThreadId}..."
+
+ match obj with
+ | :? CancellationTokenSource as source -> source.Cancel()
+ | _ -> ()
+
+let ts = new CancellationTokenSource()
+let thread = Thread(ParameterizedThreadStart cancelToken)
+thread.Start ts
+
+let t =
+ Task.Run(fun () ->
+ Task.Delay(5000).Wait()
+ printfn "Task ended delay...")
+
+try
+ printfn $"About to wait completion of task {t.Id}"
+ let result = t.Wait(1510, ts.Token)
+ printfn $"Wait completed normally: {result}"
+ printfn $"The task status: {t.Status:G}"
+
+with :? OperationCanceledException as e ->
+ printfn $"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
+ Thread.Sleep 4000
+ printfn $"After sleeping, the task status: {t.Status:G}"
+ ts.Dispose()
+
+// The example displays output like the following if the wait is canceled by
+// the cancellation token:
+// About to wait completion of task 1
+// Canceling the cancellation token from thread 3...
+// OperationCanceledException: The wait has been canceled. Task status: Running
+// Task ended delay...
+// After sleeping, the task status: RanToCompletion
+// The example displays output like the following if the wait is canceled by
+// the timeout interval expiring:
+// About to wait completion of task 1
+// Wait completed normally: False
+// The task status: Running
+// Canceling the cancellation token from thread 3...
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/WaitAny1.fs b/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/WaitAny1.fs
new file mode 100644
index 00000000000..08857bdcd39
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/WaitAny1.fs
@@ -0,0 +1,27 @@
+module WaitAny1
+//
+open System.Threading
+open System.Threading.Tasks
+
+let tasks =
+ [| for factor = 0 to 4 do
+ Task.Run(fun () -> Thread.Sleep(factor * 250 + 50)) |]
+
+let index = Task.WaitAny tasks
+printfn $"Wait ended because task #{tasks[index].Id} completed."
+printfn "\nCurrent Status of Tasks:"
+
+for t in tasks do
+ printfn $" Task {t.Id}: {t.Status}"
+
+
+// The example displays output like the following:
+// Wait ended because task #1 completed.
+//
+// Current Status of Tasks:
+// Task 1: RanToCompletion
+// Task 2: Running
+// Task 3: Running
+// Task 4: Running
+// Task 5: Running
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/fs.fsproj
new file mode 100644
index 00000000000..ea54b8657b4
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/fs.fsproj
@@ -0,0 +1,10 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll3.fs b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll3.fs
new file mode 100644
index 00000000000..0401a989a6b
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll3.fs
@@ -0,0 +1,52 @@
+module WhenAll3
+
+//
+open System
+open System.Net.NetworkInformation
+open System.Threading
+open System.Threading.Tasks
+
+let mutable failed = 0
+
+let urls =
+ [| "www.adatum.com"
+ "www.cohovineyard.com"
+ "www.cohowinery.com"
+ "www.northwindtraders.com"
+ "www.contoso.com" |]
+
+let tasks =
+ urls
+ |> Array.map (fun url ->
+ Task.Run(fun () ->
+ let png = new Ping()
+
+ try
+ let reply = png.Send url
+
+ if reply.Status <> IPStatus.Success then
+ Interlocked.Increment &failed |> ignore
+ raise (TimeoutException $"Unable to reach {url}.")
+ with :? PingException ->
+ Interlocked.Increment &failed |> ignore
+ reraise ()))
+
+let main =
+ task {
+ let t = Task.WhenAll tasks
+
+ try
+ do! t
+ with _ ->
+ ()
+
+ if t.Status = TaskStatus.RanToCompletion then
+ printfn "All ping attempts succeeded."
+ elif t.Status = TaskStatus.Faulted then
+ printfn $"{failed} ping attempts failed"
+ }
+
+main.Wait()
+// The example displays output like the following:
+// 5 ping attempts failed
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll4.fs b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll4.fs
new file mode 100644
index 00000000000..925644553f8
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll4.fs
@@ -0,0 +1,48 @@
+module WhenAll4
+
+//
+open System
+open System.Net.NetworkInformation
+open System.Threading
+open System.Threading.Tasks
+
+let mutable failed = 0
+
+let urls =
+ [ "www.adatum.com"
+ "www.cohovineyard.com"
+ "www.cohowinery.com"
+ "www.northwindtraders.com"
+ "www.contoso.com" ]
+
+let tasks =
+ urls
+ |> List.map (fun url ->
+ Task.Run(fun () ->
+ let png = new Ping()
+
+ try
+ let reply = png.Send url
+
+ if reply.Status <> IPStatus.Success then
+ Interlocked.Increment &failed |> ignore
+ raise (TimeoutException $"Unable to reach {url}.")
+ with :? PingException ->
+ Interlocked.Increment &failed |> ignore
+ reraise ()))
+
+let t = Task.WhenAll tasks
+
+try
+ t.Wait()
+with _ ->
+ ()
+
+if t.Status = TaskStatus.RanToCompletion then
+ printfn "All ping attempts succeeded."
+elif t.Status = TaskStatus.Faulted then
+ printfn $"{failed} ping attempts failed"
+
+// The example displays output like the following:
+// 5 ping attempts failed
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/fs.fsproj b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/fs.fsproj
new file mode 100644
index 00000000000..cb62ab5ddbc
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/fs.fsproj
@@ -0,0 +1,13 @@
+
+
+ Exe
+ net7.0
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall1.fs b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall1.fs
new file mode 100644
index 00000000000..18e4b43805f
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall1.fs
@@ -0,0 +1,55 @@
+module whenall1
+//
+open System
+open System.Threading.Tasks
+
+let tasks =
+ [| for i = 1 to 10 do
+ let delayInterval = 18 * i
+
+ task {
+ let mutable total = 0L
+ do! Task.Delay delayInterval
+ let rnd = Random()
+
+ for _ = 1 to 1000 do
+ total <- total + (rnd.Next(0, 1000) |> int64)
+
+ return total
+ } |]
+
+let continuation = Task.WhenAll tasks
+
+try
+ continuation.Wait()
+
+with :? AggregateException ->
+ ()
+
+if continuation.Status = TaskStatus.RanToCompletion then
+ for result in continuation.Result do
+ printfn $"Mean: {float result / 1000.:N2}, n = 1,000"
+
+ let grandTotal = continuation.Result |> Array.sum
+
+ printfn $"\nMean of Means: {float grandTotal / 10000.:N2}, n = 10,000"
+
+// Display information on faulted tasks.
+else
+ for t in tasks do
+ printfn $"Task {t.Id}: {t.Status}"
+
+// The example displays output like the following:
+// Mean: 506.34, n = 1,000
+// Mean: 504.69, n = 1,000
+// Mean: 489.32, n = 1,000
+// Mean: 505.96, n = 1,000
+// Mean: 515.31, n = 1,000
+// Mean: 499.94, n = 1,000
+// Mean: 496.92, n = 1,000
+// Mean: 508.58, n = 1,000
+// Mean: 494.88, n = 1,000
+// Mean: 493.53, n = 1,000
+//
+// Mean of Means: 501.55, n = 10,000
+//
diff --git a/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall2.fs b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall2.fs
new file mode 100644
index 00000000000..8e41a612a02
--- /dev/null
+++ b/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall2.fs
@@ -0,0 +1,55 @@
+module whenall2
+//
+open System
+open System.Threading.Tasks
+
+let tasks =
+ [| for i = 1 to 10 do
+ let delayInterval = 18 * i
+
+ task {
+ let mutable total = 0L
+ do! Task.Delay delayInterval
+ let rnd = Random()
+
+ for _ = 1 to 1000 do
+ total <- total + (rnd.Next(0, 1000) |> int64)
+
+ return total
+ } |]
+
+let continuation = Task.WhenAll tasks
+
+try
+ continuation.Wait()
+
+with :? AggregateException ->
+ ()
+
+if continuation.Status = TaskStatus.RanToCompletion then
+ for result in continuation.Result do
+ printfn $"Mean: {float result / 1000.:N2}, n = 1,000"
+
+ let grandTotal = Array.sum continuation.Result
+
+ printfn $"\nMean of Means: {float grandTotal / 10000.:N2}, n = 10,000"
+
+// Display information on faulted tasks.
+else
+ for t in tasks do
+ printfn $"Task {t.Id}: {t.Status}"
+
+// The example displays output like the following:
+// Mean: 506.38, n = 1,000
+// Mean: 501.01, n = 1,000
+// Mean: 505.36, n = 1,000
+// Mean: 492.00, n = 1,000
+// Mean: 508.36, n = 1,000
+// Mean: 503.99, n = 1,000
+// Mean: 504.95, n = 1,000
+// Mean: 508.58, n = 1,000
+// Mean: 490.23, n = 1,000
+// Mean: 501.59, n = 1,000
+//
+// Mean of Means: 502.00, n = 10,000
+//
diff --git a/xml/System.Threading.Tasks/Task.xml b/xml/System.Threading.Tasks/Task.xml
index 121dbfdc3c8..d3f84781505 100644
--- a/xml/System.Threading.Tasks/Task.xml
+++ b/xml/System.Threading.Tasks/Task.xml
@@ -102,6 +102,7 @@
Because task `t4` executes synchronously, it executes on the main application thread. The remaining tasks execute asynchronously typically on one or more thread pool threads.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/startnew.cs" id="Snippet01":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew.fs" id="Snippet01":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/startnew.vb" id="Snippet01":::
@@ -109,11 +110,13 @@
instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static method. The method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations:
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/run1.cs" id="Snippet6":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/run1.fs" id="Snippet6":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/run1.vb" id="Snippet6":::
An alternative, and the most common method to start a task in .NET Framework 4, is the static method. The property returns a object. Overloads of the method let you specify parameters to pass to the task creation options and a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/startnew1.cs" id="Snippet7":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/startnew1.fs" id="Snippet7":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/startnew1.vb" id="Snippet7":::
For more complete examples, see [Task-based Asynchronous Programming](/dotnet/standard/parallel-programming/task-based-asynchronous-programming).
@@ -131,11 +134,13 @@
The following example calls the parameterless method to wait unconditionally until a task completes. The task simulates work by calling the method to sleep for two seconds.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/Wait1.cs" id="Snippet8":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait1.fs" id="Snippet8":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/Wait1.vb" id="Snippet8":::
You can also conditionally wait for a task to complete. The and methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/Wait2.cs" id="Snippet9":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/Wait2.fs" id="Snippet9":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/Wait2.vb" id="Snippet9":::
You can also supply a cancellation token by calling the and methods. If the token's property is `true` or becomes `true` while the method is executing, the method throws an .
@@ -143,16 +148,19 @@
In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. For this purpose, you can call one of the overloads of the method. The following example creates three tasks, each of which sleeps for an interval determined by a random number generator. The method waits for the first task to complete. The example then displays information about the status of all three tasks.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/WhenAny1.cs" id="Snippet10":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/WhenAny1.fs" id="Snippet10":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAny1.vb" id="Snippet10":::
You can also wait for all of a series of tasks to complete by calling the method. The following example creates ten tasks, waits for all ten to complete, and then displays their status.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/WaitAll1.cs" id="Snippet11":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll1.fs" id="Snippet11":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAll1.vb" id="Snippet11":::
Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the `Wait` method, as the following example shows. It launches 12 tasks, three of which complete normally and three of which throw an exception. Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. Exceptions are thrown in the method call and are handled by a `try`/`catch` block.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/WaitAll2.cs" id="Snippet12":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/WaitAll2.fs" id="Snippet12":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/WaitAll2.vb" id="Snippet12":::
For more information on exception handling in task-based asynchronous operations, see [Exception Handling](/dotnet/standard/parallel-programming/exception-handling-task-parallel-library).
@@ -240,11 +248,13 @@
The following example uses the constructor to create tasks that retrieve the filenames in specified directories. All tasks write the file names to a single object. The example then calls the method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the object.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/ctor1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/ctor1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/ctor1.vb" id="Snippet1":::
The following example is identical, except that it used the method to instantiate and run the task in a single operation. The method returns the object that represents the task.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run2.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run2.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run2.vb" id="Snippet1":::
]]>
@@ -305,6 +315,7 @@
The following example calls the constructor to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method. The method is then called to start the task.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run4.cs" id="Snippet4":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run4.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/run4.vb" id="Snippet4":::
]]>
@@ -416,6 +427,7 @@
The following example defines an array of 6-letter words. Each word is then passed as an argument to the constructor, whose delegate scrambles the characters in the word, then displays the original word and its scrambled version.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/startnew3.cs" id="Snippet3":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/startnew3.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.ctor/vb/startnew3.vb" id="Snippet3":::
]]>
@@ -877,6 +889,7 @@ When an asynchronous method awaits a directly
The following example defines a task that populates an array with 100 random date and time values. It uses the method to select the earliest and the latest date values once the array is fully populated.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/ContinueWith/continuewith1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/ContinueWith/continuewith1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.continuewith/vb/continuewith1.vb" id="Snippet1":::
Because a console application may terminate before the continuation task executes, the method is called to ensure that the continuation finishes executing before the example ends.
@@ -1566,6 +1579,7 @@ End Sub
The following example shows how to use the ContinueWith method:
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/continuationsimple.cs" id="Snippet03":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationsimple.fs" id="Snippet03":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/continuationsimple.vb" id="Snippet03":::
]]>
@@ -2075,6 +2089,7 @@ End Sub
The following example shows how to use the ContinueWith method with continuation options:
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/continuationoptions.cs" id="Snippet04":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/continuationoptions.fs" id="Snippet04":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/continuationoptions.vb" id="Snippet04":::
]]>
@@ -2313,11 +2328,13 @@ End Sub
- At the beginning of the task, as the following example shows.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay5.cs" id="Snippet5":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay5.fs" id="Snippet5":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay5.vb" id="Snippet5":::
- Sometime while the task is executing. In this case, the call to the method executes as a child task within a task, as the following example shows. Note that since the task that calls the method executes asynchronously, the parent task must wait for it to complete by using the `await` keyword.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay5.cs" id="Snippet7":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay5.fs" id="Snippet7":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay5.vb" id="Snippet7":::
After the specified time delay, the task is completed in the state.
@@ -2333,6 +2350,7 @@ End Sub
The following example shows a simple use of the method.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay1.vb" id="Snippet1":::
]]>
@@ -2401,6 +2419,7 @@ End Sub
The following example shows a simple use of the method.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay2.cs" id="Snippet2":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay2.fs" id="Snippet2":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay2.vb" id="Snippet2":::
]]>
@@ -2476,6 +2495,7 @@ End Sub
The following example launches a task that includes a call to the method with a one second delay. Before the delay interval elapses, the token is cancelled. The output from the example shows that, as a result, a is thrown, and the tasks' property is set to .
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay3.cs" id="Snippet3":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay3.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay3.vb" id="Snippet3":::
]]>
@@ -2548,6 +2568,7 @@ End Sub
The following example launches a task that includes a call to the method with a 1.5 second delay. Before the delay interval elapses, the token is cancelled. The output from the example shows that, as a result, a is thrown, and the tasks' property is set to .
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Delay/delay4.cs" id="Snippet4":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Delay/delay4.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.delay/vb/delay4.vb" id="Snippet4":::
Note that this example includes a potential race condition: it depends on the task asynchronously executing the delay when the token is cancelled. Although the 1.5 second delay from the call to the method makes that assumption likely, it is nevertheless possible that the call to the method could return before the token is cancelled. In that case, the example produces the following output:
@@ -2787,6 +2808,7 @@ Task t Status: RanToCompletion, Result: 42
The following example uses the static property to make two calls to the method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Factory/factory1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Factory/factory1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.factory/vb/factory1.vb" id="Snippet1":::
]]>
@@ -2996,6 +3018,7 @@ Task t Status: RanToCompletion, Result: 42
The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. Rather than executing a longer code path that instantiates a object and retrieves the value of its property for each file in the directory, the example simply calls the method to create a faulted task if a particular subdirectory does not exist.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1":::
]]>
@@ -3063,6 +3086,7 @@ Starting in .NET 6, for some `TResult` types and some result values, this method
The following example is a command-line utility that calculates the number of bytes in the files in each directory whose name is passed as a command-line argument. Rather than executing a longer code path that instantiates a object and retrieves the value of its property for each file in the directory, the example simply calls the method to create a task whose property is zero (0) if a directory has no files.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/FromExceptionTResult/fromresult1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.fromresult/vb/fromresult1.vb" id="Snippet1":::
]]>
@@ -3464,11 +3488,13 @@ This method is intended for compiler use rather than use directly in code.
The following example defines a `ShowThreadInfo` method that displays the of the current thread. It is called directly from the application thread, and is called from the delegate passed to the method.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run11.cs" id="Snippet11":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run11.fs" id="Snippet11":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run11.vb" id="Snippet11":::
The following example is similar to the previous one, except that it uses a lambda expression to define the code that the task is to execute.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run6.cs" id="Snippet3":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run6.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run6.vb" id="Snippet3":::
The examples show that the asynchronous task executes on a different thread than the main application thread.
@@ -3478,6 +3504,7 @@ This method is intended for compiler use rather than use directly in code.
The following example illustrates the method. It defines an array of directory names and starts a separate task to retrieve the file names in each directory. All tasks write the file names to a single object. The example then calls the method to ensure that all tasks have completed, and then displays a count of the total number of file names written to the object.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run2.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run2.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run2.vb" id="Snippet1":::
]]>
@@ -3605,6 +3632,7 @@ This method is intended for compiler use rather than use directly in code.
The following example calls the method to create a task that iterates the files in the C:\Windows\System32 directory. The lambda expression calls the method to add information about each file to a object. Each detached nested task invoked by the loop checks the state of the cancellation token and, if cancellation is requested, calls the method. The method throws an exception that is handled in a `catch` block when the calling thread calls the method.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run41.cs" id="Snippet4":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run41.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run4.vb" id="Snippet4":::
]]>
@@ -3800,6 +3828,7 @@ This method is intended for compiler use rather than use directly in code.
The following example counts the approximate number of words in text files that represent published books. Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. The method is called to ensure that all tasks have completed before displaying the word count of each book to the console.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/run31.cs" id="Snippet2":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/run31.fs" id="Snippet2":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/run3.vb" id="Snippet2":::
The regular expression `\p{P}*\s+` matches zero, one, or more punctuation characters followed by one or more white-space characters. It assumes that the total number of matches equals the approximate word count.
@@ -3942,6 +3971,7 @@ This method is intended for compiler use rather than use directly in code.
The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example shows possible output.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run7.cs" id="Snippet7":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run7.fs" id="Snippet7":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run7.vb" id="Snippet7":::
Instead of using the property to examine exceptions, the example iterates all tasks to determine which have completed successfully and which have been cancelled. For those that have completed, it displays the value returned by the task.
@@ -3949,6 +3979,7 @@ This method is intended for compiler use rather than use directly in code.
Because cancellation is cooperative, each task can decide how to respond to cancellation. The following example is like the first, except that, once the token is cancelled, tasks return the number of iterations they've completed rather than throw an exception.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run28.cs" id="Snippet28":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run28.fs" id="Snippet28":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run28.vb" id="Snippet28":::
The example still must handle the exception, since any tasks that have not started when cancellation is requested still throw an exception.
@@ -4024,6 +4055,7 @@ This method is intended for compiler use rather than use directly in code.
The following example compares a task executed by calling the method with one executed asynchronously. In both cases, the tasks execute identical lambda expressions that display the task ID and the ID of the thread on which the task is running. The task calculates the sum of the integers between 1 and 1,000,000. As the output from the example shows, the task executed by calling the method runs on the application thread, while the asynchronous task does not.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/RunSynchronously/runsynchronously1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/RunSynchronously/runsynchronously1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.runsynchronously/vb/runsynchronously1.vb" id="Snippet1":::
]]>
@@ -4155,6 +4187,7 @@ This method is intended for compiler use rather than use directly in code.
The following example calls the constructor to instantiate a new object that displays its task ID and managed thread ID and then executes a loop. It then calls the method to execute the task. Since this is a console app, the call to the method is necessary to prevent the app from terminating before the task finishes execution.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Start/Start1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Start/Start1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.start/vb/Start1.vb" id="Snippet1":::
]]>
@@ -4274,6 +4307,7 @@ This method is intended for compiler use rather than use directly in code.
The following example creates 20 tasks that will loop until a counter is incremented to a value of 2 million. When the first 10 tasks reach 2 million, the cancellation token is cancelled, and any tasks whose counters have not reached 2 million are cancelled. The example then examines the property of each task to indicate whether it completed successfully or was cancelled. For those that completed, it displays the value returned by the task.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/.ctor/Run7.cs" id="Snippet7":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/.ctor/Run7.fs" id="Snippet7":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.run/vb/Run7.vb" id="Snippet7":::
]]>
@@ -4443,6 +4477,7 @@ This member is an explicit interface member implementation. It can be used only
The following example starts a task that generates one million random integers between 0 and 100 and computes their mean. The example uses the method to ensure that the task completes before the application terminates. Otherwise, because this is a console application, the example would terminate before the task can compute and display the mean.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/wait1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait1.vb" id="Snippet1":::
]]>
@@ -4517,6 +4552,7 @@ This member is an explicit interface member implementation. It can be used only
The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/Wait5.cs" id="Snippet5":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait5.fs" id="Snippet5":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/Wait5.vb" id="Snippet5":::
]]>
@@ -4591,6 +4627,7 @@ This member is an explicit interface member implementation. It can be used only
The following example illustrates the simple use of a cancellation token to cancel waiting for a task's completion. A task is launched, calls the method to cancel any of the token source's cancellation tokens, and then delays for five seconds. Note that the task itself has not been passed the cancellation token and is not cancelable. The application thread calls the task's method to wait for the task to complete, but the wait is canceled once the cancellation token is cancelled and an is thrown. The exception handler reports the exception and then sleeps for six seconds. As the output from the example shows, that delay allows the task to complete in the state.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/wait3.cs" id="Snippet3":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait3.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait3.vb" id="Snippet3":::
]]>
@@ -4665,6 +4702,7 @@ This member is an explicit interface member implementation. It can be used only
The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. The example uses the method to wait for the application to complete within 150 milliseconds. If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. If the timeout interval has elapsed, the example displays a message before it terminates.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/Wait6.cs" id="Snippet6":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Wait/Wait6.fs" id="Snippet6":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/Wait6.vb" id="Snippet6":::
]]>
@@ -4751,6 +4789,7 @@ This member is an explicit interface member implementation. It can be used only
The following example calls the method to provide both a timeout value and a cancellation token that can end the wait for a task's completion. A new thread is started and executes the `CancelToken` method, which pauses and then calls the method to cancel the cancellation tokens. A task is then launched and delays for 5 seconds. The method is then called to wait for the task's completion and is provided both a brief timeout value and a cancellation token.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Wait/wait4.cs" id="Snippet4":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Wait/wait4.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.wait/vb/wait4.vb" id="Snippet4":::
Note that the precise output from the example depends on whether the wait was canceled because of the cancellation token or because the timeout interval elapsed.
@@ -4890,6 +4929,7 @@ timeout is greater than
The following example starts 10 tasks, each of which is passed an index as a state object. Tasks with an index from two to five throw exceptions. The call to the method wraps all exceptions in an object and propagates it to the calling thread.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/Overview/waitall.cs" id="Snippet02":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/Overview/waitall.fs" id="Snippet02":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task/vb/waitall.vb" id="Snippet02":::
]]>
@@ -5244,6 +5284,7 @@ timeout is greater than
The following example launches five tasks, each of which sleeps for a minimum of 50 milliseconds or a maximum of 1,050 milliseconds. The method then waits for any of the tasks to complete. The example displays the task ID of the task that ended the wait, as well as the current status of all the tasks.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WaitAny/WaitAny1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/WaitAny/WaitAny1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/System.Threading.Tasks.Task.WaitAny/vb/WaitAny1.vb" id="Snippet1":::
]]>
@@ -5648,6 +5689,7 @@ timeout is greater than
The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a `List` collection that is passed to the method. After the call to the method ensures that all threads have completed, the example examines the property to determine whether any tasks have faulted.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/WhenAll4.cs" id="Snippet4":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll4.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/WhenAll4.vb" id="Snippet4":::
]]>
@@ -5728,6 +5770,7 @@ timeout is greater than
The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a `List` collection that is converted to an array and passed to the method. After the call to the method ensures that all threads have completed, the example examines the property to determine whether any tasks have faulted.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/WhenAll3.cs" id="Snippet3":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/WhenAll3.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/WhenAll3.vb" id="Snippet3":::
]]>
@@ -5802,6 +5845,7 @@ timeout is greater than
The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. The method is used to delay instantiation of the random number generators so that they are not created with identical seed values. The call to the method then returns an array that contains the mean computed by each task. These are then used to calculate the overall mean.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/whenall1.cs" id="Snippet1":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/whenall1.vb" id="Snippet1":::
In this case, the ten individual tasks are stored in a object. implements the interface.
@@ -5885,6 +5929,7 @@ timeout is greater than
The following example creates ten tasks, each of which instantiates a random number generator that creates 1,000 random numbers between 1 and 1,000 and computes their mean. In this case, the ten individual tasks are stored in a `Task` array. The method is used to delay instantiation of the random number generators so that they are not created with identical seed values. The call to the method then returns an array that contains the mean computed by each task. These are then used to calculate the overall mean.
:::code language="csharp" source="~/snippets/csharp/System.Threading.Tasks/Task/WhenAll/whenall2.cs" id="Snippet2":::
+ :::code language="fsharp" source="~/snippets/fsharp/System.Threading.Tasks/Task/WhenAll/whenall2.fs" id="Snippet2":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.threading.tasks.task.whenall/vb/whenall2.vb" id="Snippet2":::
]]>