dotnet / dotnet/dotnet-api-docs

Access to token when the Task action is defined in another scope

Open
#763 3 comments 0 reactions 0 assignees View on GitHub
area-System.Threading.Tasks example-request Pri1 unspecified/svc
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

I'm using the overload `Task.Run(Action, CancellationToken)`. The example code shows how to handle the cancellation, but the `token` variable inside the anonymous action appears to be available because it is declared in the outer scope. How is a cancellation token accessed within the action body when the action is defined in another scope, such as in another class. I have made this work by passing the token both as second argument to Task.Run and as an argument to my action method, but surely it is not intended that this token should have to be passed twice (redundantly). Since the token is passed to Task.Run it must be available inside the action by some local reference.

Enhancing the example code with this more general usage would be helpful.

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: 53ffa5ba-8804-d68e-50e8-a28c25506dc3
* Version Independent ID: 6d39fed4-8dc0-1907-8d92-9e30c0907369
* Content: [Task.Run Method (System.Threading.Tasks)](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=netframework-4.7.1#System_Threading_Tasks_Task_Run_System_Action_System_Threading_CancellationToken_)
* Content Source: [xml/System.Threading.Tasks/Task.xml](https://github.com/dotnet/dotnet-api-docs/blob/master/xml/System.Threading.Tasks/Task.xml)
* Service: **unspecified**
* GitHub Login: @dotnet-bot
* Microsoft Alias: **dotnetcontent**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.