Skip to content

Commit 1f283be

Browse files
authored
Change TaskCanceledException to OperationCanceledException (#37364)
1 parent c0e7dbd commit 1f283be

File tree

8 files changed

+44
-37
lines changed

8 files changed

+44
-37
lines changed

docs/core/extensions/snippets/workers/6.0/windows-service/WindowsBackgroundService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
2222
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
2323
}
2424
}
25-
catch (TaskCanceledException)
25+
catch (OperationCanceledException)
2626
{
2727
// When the stopping token is canceled, for example, a call made from services.msc,
2828
// we shouldn't exit with a non-zero exit code. In other words, this is expected...

docs/core/extensions/snippets/workers/7.0/windows-service/WindowsBackgroundService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
2222
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
2323
}
2424
}
25-
catch (TaskCanceledException)
25+
catch (OperationCanceledException)
2626
{
2727
// When the stopping token is canceled, for example, a call made from services.msc,
2828
// we shouldn't exit with a non-zero exit code. In other words, this is expected...

docs/csharp/asynchronous-programming/snippets/cancel-tasks/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ static async Task Main()
5959
await sumPageSizesTask;
6060
Console.WriteLine("Download task completed before cancel request was processed.");
6161
}
62-
catch (TaskCanceledException)
62+
catch (OperationCanceledException)
6363
{
6464
Console.WriteLine("Download task has been cancelled.");
6565
}

docs/fundamentals/networking/snippets/httpclient/Program.Cancellation.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ static async Task WithCancellationAsync(HttpClient httpClient)
1212
using var response = await httpClient.GetAsync(
1313
"http://localhost:5001/sleepFor?seconds=100", cts.Token);
1414
}
15-
catch (TaskCanceledException ex) when (cts.IsCancellationRequested)
15+
catch (OperationCanceledException ex) when (cts.IsCancellationRequested)
1616
{
1717
// When the token has been canceled, it is not a timeout.
1818
Console.WriteLine($"Canceled: {ex.Message}");

docs/fundamentals/networking/snippets/httpclient/Program.CancellationInnerTimeout.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ static async Task WithCancellationAndInnerTimeoutAsync(HttpClient httpClient)
1111
using var response = await httpClient.GetAsync(
1212
"http://localhost:5001/sleepFor?seconds=100");
1313
}
14-
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException tex)
14+
catch (OperationCanceledException ex) when (ex.InnerException is TimeoutException tex)
1515
{
1616
Console.WriteLine($"Timed out: {ex.Message}, {tex.Message}");
1717
}

samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public static async Task Main()
6161
// Optional: Observe the change in the Status property on the task.
6262
// It is not necessary to wait on tasks that have canceled. However,
6363
// if you do wait, you must enclose the call in a try-catch block to
64-
// catch the TaskCanceledExceptions that are thrown. If you do
64+
// catch the OperationCanceledExceptions that are thrown. If you do
6565
// not wait, no exception is thrown if the token that was passed to the
6666
// Task.Run method is the same token that requested the cancellation.
6767
}

samples/snippets/visualbasic/VS_Snippets_Misc/tpl_cancellation/vb/cancel1.vb

Lines changed: 30 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ Module Example
88
Dim tokenSource As New CancellationTokenSource()
99
Dim token As CancellationToken = tokenSource.Token
1010

11-
' Store references to the tasks so that we can wait on them and
12-
' observe their status after cancellation.
11+
' Store references to the tasks so that we can wait on them and
12+
' observe their status after cancellation.
1313
Dim t As Task
1414
Dim tasks As New ConcurrentBag(Of Task)()
1515

@@ -18,26 +18,26 @@ Module Example
1818
Console.WriteLine("To terminate the example, press 'c' to cancel and exit...")
1919
Console.WriteLine()
2020

21-
' Request cancellation of a single task when the token source is canceled.
22-
' Pass the token to the user delegate, and also to the task so it can
21+
' Request cancellation of a single task when the token source is canceled.
22+
' Pass the token to the user delegate, and also to the task so it can
2323
' handle the exception correctly.
2424
t = Task.Factory.StartNew(Sub() DoSomeWork(1, token), token)
2525
Console.WriteLine("Task {0} executing", t.Id)
2626
tasks.Add(t)
2727

28-
' Request cancellation of a task and its children. Note the token is passed
29-
' to (1) the user delegate and (2) as the second argument to StartNew, so
28+
' Request cancellation of a task and its children. Note the token is passed
29+
' to (1) the user delegate and (2) as the second argument to StartNew, so
3030
' that the task instance can correctly handle the OperationCanceledException.
3131
t = Task.Factory.StartNew(Sub()
32-
' Create some cancelable child tasks.
32+
' Create some cancelable child tasks.
3333
Dim tc As Task
3434
For i As Integer = 3 To 10
35-
' For each child task, pass the same token
35+
' For each child task, pass the same token
3636
' to each user delegate and to StartNew.
3737
tc = Task.Factory.StartNew(Sub(iteration) DoSomeWork(iteration, token), i, token)
3838
Console.WriteLine("Task {0} executing", tc.Id)
3939
tasks.Add(tc)
40-
' Pass the same token again to do work on the parent task.
40+
' Pass the same token again to do work on the parent task.
4141
' All will be signaled by the call to tokenSource.Cancel below.
4242
DoSomeWork(2, token)
4343
Next
@@ -47,30 +47,29 @@ Module Example
4747
Console.WriteLine("Task {0} executing", t.Id)
4848
tasks.Add(t)
4949

50-
' Request cancellation from the UI thread.
50+
' Request cancellation from the UI thread.
5151
Dim ch As Char = Console.ReadKey().KeyChar
5252
If ch = "c"c Or ch = "C"c Then
5353
tokenSource.Cancel()
5454
Console.WriteLine(vbCrLf + "Task cancellation requested.")
5555

56-
' Optional: Observe the change in the Status property on the task.
57-
' It is not necessary to wait on tasks that have canceled. However,
58-
' if you do wait, you must enclose the call in a try-catch block to
59-
' catch the TaskCanceledExceptions that are thrown. If you do
60-
' not wait, no exception is thrown if the token that was passed to the
61-
' StartNew method is the same token that requested the cancellation.
56+
' Optional: Observe the change in the Status property on the task.
57+
' It is not necessary to wait on tasks that have canceled. However,
58+
' if you do wait, you must enclose the call in a try-catch block to
59+
' catch the OperationCanceledExceptions that are thrown. If you do
60+
' not wait, no exception is thrown if the token that was passed to the
61+
' StartNew method is the same token that requested the cancellation.
6262
End If
6363

6464
Try
6565
Task.WaitAll(tasks.ToArray())
6666
Catch e As AggregateException
6767
Console.WriteLine()
6868
Console.WriteLine("AggregateException thrown with the following inner exceptions:")
69-
' Display information about each exception.
69+
' Display information about each exception.
7070
For Each v In e.InnerExceptions
71-
If TypeOf v Is TaskCanceledException
72-
Console.WriteLine(" TaskCanceledException: Task {0}",
73-
DirectCast(v, TaskCanceledException).Task.Id)
71+
If TypeOf v Is OperationCanceledException Then
72+
Console.WriteLine(" The operation was canceled.")
7473
Else
7574
Console.WriteLine(" Exception: {0}", v.GetType().Name)
7675
End If
@@ -80,14 +79,14 @@ Module Example
8079
tokenSource.Dispose()
8180
End Try
8281

83-
' Display status of all tasks.
82+
' Display status of all tasks.
8483
For Each t In tasks
8584
Console.WriteLine("Task {0} status is now {1}", t.Id, t.Status)
8685
Next
8786
End Sub
8887

8988
Sub DoSomeWork(ByVal taskNum As Integer, ByVal ct As CancellationToken)
90-
' Was cancellation already requested?
89+
' Was cancellation already requested?
9190
If ct.IsCancellationRequested = True Then
9291
Console.WriteLine("Task {0} was cancelled before it got started.",
9392
taskNum)
@@ -96,13 +95,13 @@ Module Example
9695

9796
Dim maxIterations As Integer = 100
9897

99-
' NOTE!!! A "TaskCanceledException was unhandled
100-
' by user code" error will be raised here if "Just My Code"
101-
' is enabled on your computer. On Express editions JMC is
102-
' enabled and cannot be disabled. The exception is benign.
103-
' Just press F5 to continue executing your code.
98+
' NOTE!!! A "TaskCanceledException was unhandled
99+
' by user code" error will be raised here if "Just My Code"
100+
' is enabled on your computer. On Express editions JMC is
101+
' enabled and cannot be disabled. The exception is benign.
102+
' Just press F5 to continue executing your code.
104103
For i As Integer = 0 To maxIterations
105-
' Do a bit of work. Not too much.
104+
' Do a bit of work. Not too much.
106105
Dim sw As New SpinWait()
107106
For j As Integer = 0 To 100
108107
sw.SpinOnce()
@@ -117,7 +116,7 @@ End Module
117116
' The example displays output like the following:
118117
' Press any key to begin tasks...
119118
' To terminate the example, press 'c' to cancel and exit...
120-
'
119+
'
121120
' Task 1 executing
122121
' Task 2 executing
123122
' Task 3 executing
@@ -130,12 +129,12 @@ End Module
130129
' Task cancellation requested.
131130
' Task 2 cancelled
132131
' Task 7 cancelled
133-
'
132+
'
134133
' AggregateException thrown with the following inner exceptions:
135134
' TaskCanceledException: Task 2
136135
' TaskCanceledException: Task 8
137136
' TaskCanceledException: Task 7
138-
'
137+
'
139138
' Task 2 status is now Canceled
140139
' Task 1 status is now RanToCompletion
141140
' Task 8 status is now Canceled
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Library</OutputType>
5+
<TargetFramework>net7.0</TargetFramework>
6+
</PropertyGroup>
7+
8+
</Project>

0 commit comments

Comments
 (0)