Skip to content

Commit 1768f03

Browse files
authored
Include a snippet on IAsyncDisposable (#46414)
* Include a snippet on IAsyncDisposable * Update task-expressions.md
1 parent ef844cc commit 1768f03

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

docs/fsharp/language-reference/task-expressions.md

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
---
22
title: Task expressions
33
description: Learn about support in the F# programming language for writing task expressions, which author .NET tasks directly.
4-
ms.date: 10/29/2021
4+
ms.date: 05/25/2025
55
---
6-
# Tasks expressions
6+
# Task expressions
77

88
This article describes support in F# for task expressions, which are similar to [async expressions](async-expressions.md) but allow you to author .NET tasks directly. Like async expressions, task expressions execute code asynchronously, that is, without blocking execution of other work.
99

@@ -55,6 +55,35 @@ Within task expressions, `use` bindings can bind to values of type <xref:System.
5555

5656
In addition to `let!`, you can use `use!` to perform asynchronous bindings. The difference between `let!` and `use!` is the same as the difference between `let` and `use`. For `use!`, the object is disposed of at the close of the current scope. Note that in F# 6, `use!` does not allow a value to be initialized to null, even though `use` does.
5757

58+
```fsharp
59+
open System
60+
open System.IO
61+
open System.Security.Cryptography
62+
task {
63+
// use IDisposable
64+
use httpClient = new Net.Http.HttpClient()
65+
// use! Task<IDisposable>
66+
use! exampleDomain = httpClient.GetAsync "https://example.com/data.enc"
67+
68+
// use IDisposable
69+
use aes = Aes.Create()
70+
aes.KeySize <- 256
71+
aes.GenerateIV()
72+
aes.GenerateKey()
73+
// do! Task
74+
do! File.WriteAllTextAsync("key.iv.txt", $"Key: {Convert.ToBase64String aes.Key}\nIV: {Convert.ToBase64String aes.IV}")
75+
76+
// use IAsyncDisposable
77+
use outputStream = File.Create "secret.enc"
78+
// use IDisposable
79+
use encryptor = aes.CreateEncryptor()
80+
// use IAsyncDisposable
81+
use cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write)
82+
// do! Task
83+
do! exampleDomain.Content.CopyToAsync cryptoStream
84+
}
85+
```
86+
5887
## Value Tasks
5988

6089
Value tasks are structs used to avoid allocations in task-based programming. A value task is an ephemeral value that's turned into a real task by using `.AsTask()`.

0 commit comments

Comments
 (0)