Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8349839
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T08:07:49+00:00 2026-06-09T08:07:49+00:00

Microsoft gives this example of CancellationToken use in .NET 4. using System; using System.Threading;

  • 0

Microsoft gives this example of CancellationToken use in .NET 4.

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
    static void Main()
    {

        var tokenSource2 = new CancellationTokenSource();
        CancellationToken ct = tokenSource2.Token;

        var task = Task.Factory.StartNew(() =>
        {

            // Were we already canceled?
            ct.ThrowIfCancellationRequested();

            bool moreToDo = true;
            while (moreToDo)
            {
                // Poll on this property if you have to do
                // other cleanup before throwing.
                if (ct.IsCancellationRequested)
                {
                    // Clean up here, then...
                    ct.ThrowIfCancellationRequested();
                }

            }
        }, tokenSource2.Token); // Pass same token to StartNew.

        tokenSource2.Cancel();

        // Just continue on this thread, or Wait/WaitAll with try-catch:
        try
        {
            task.Wait();
        }
        catch (AggregateException e)
        {
            foreach (var v in e.InnerExceptions)
                Console.WriteLine(e.Message + " " + v.Message);
        }

        Console.ReadKey();
    }
}

However, my understanding is that if a variable is modified on one thread, another thread might not get the modified value, due to caching. And since the CancellationToken is cancelled on the main thread, how is the Task thread assured that the CancellationToken it is checking is actually up-to-date?

Why isn’t it possible for the Task to be reading a cached value of the token?

Note: My motivation in asking this arises from wondering whether I need my CancellationToken instance variables to be volatile.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T08:07:51+00:00Added an answer on June 9, 2026 at 8:07 am

    This is handled internally within CancellationTokenSource. The private variable used to track the CTS’s state is marked volatile, which prevents the internal state check from being stale.

    My motivation in asking this arises from wondering whether I need my CancellationToken instance variables to be volatile.

    You do not need to do this, as the checking is handled internally, and already handled properly for you.

    Basically, when you create a CancellationToken from the CancellationTokenSource, the token contains a reference to the original source. This reference can never change, so the call to ThrowIfCancellationRequested checks the state of the source internally. Since the source state is itself volatile, it’s never “stale” data.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

MSDN gives this example of a deep copy ( http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx ) public class Person
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation How is this url mapped to .NET namespaces? Can you give an example
Example: USE AnotherDB -- This works - same ID as from other DB SELECT
I just created a basic ASP.NET website using Microsoft's walkthrough here . It has
I'm usng this: http://schemas.microsoft.com/cdo/configuration/smtpauthenticate The schema is down? My software doesn't work anymore. Gives
the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least
http://msdn.microsoft.com/en-us/library/hh680905(v=pandp.50).aspx Transient Fault Handling gives the ability to handle connection errors etc. SaveChangesWithRetries() says
Microsoft recently released to preview Azure web sites. I had been hoping that this
i have created project referring to http://weblogs.asp.net/johnkatsiotis/archive/2008/07/23/asp-net-ajax-4-0-template-example.aspx this example . now i want to
I have written a runtime-created dialog class that doesn't use any resource files based

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.