Skip to content

[API Proposal]: Introduce TimeProvider extension method to create a CTS to be cancelled after a specified time period. #85080

Closed

Description

@tarekgh

Background and motivation

A new constructor called CancellationTokenSource(TimeSpan, TimeProvider) has been introduced for creating a CTS object that automatically gets cancelled after a specified period using the TimeProvider. However, this constructor is only available on .NET 8.0. For users who are using TimeProvider on down-level versions, they will need to write their own code to achieve the same functionality. An example of such code is given below.

        private static void CancelAfter(TimeProvider provider, CancellationTokenSource cts, TimeSpan delay)
        {
            if (provider == TimeProvider.System)
            {
                cts.CancelAfter(delay);
            }
            else
            {
                ITimer timer = provider.CreateTimer(s => ((CancellationTokenSource)s).Cancel(), cts, delay, Timeout.InfiniteTimeSpan);
                cts.Token.Register(t => ((ITimer)t).Dispose(), timer);
            }
        }

The experience would be unsatisfactory when users want to write a ns2.0 library code that works in all supported framework versions.

API Proposal

namespace System.Threading.Tasks
{
    public static class TimeProviderTaskExtensions
    {

        /// <summary>Initializes a new instance of the <see cref="CancellationTokenSource"/> class that will be canceled after the specified <see cref="TimeSpan"/>. </summary>
        /// <param name="timeProvider">The <see cref="TimeProvider"/> with which to interpret the <paramref name="delay"/>. </param>
        /// <param name="delay">The time interval to wait before canceling this <see cref="CancellationTokenSource"/>. </param>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="delay"/>'s <see cref="TimeSpan.TotalMilliseconds"/> is less than -1 or greater than <see cref="uint.MaxValue"/> - 1. </exception>
        /// <remarks>
        /// The countdown for the delay starts during the call to the constructor.  When the delay expires,
        /// the constructed <see cref="CancellationTokenSource"/> is canceled if it has
        /// not been canceled already. Subsequent calls to CancelAfter will reset the delay for the constructed
        /// <see cref="CancellationTokenSource"/> if it has not been canceled already.
        /// </remarks>
        public static CancellationTokenSource CreateCancellationTokenSource(this TimeProvider timeProvider, TimeSpan delay) ;
    }
}

API Usage

CancellationTokenSource  cts = TimeProvider.System.CreateCancellationTokenSource(TimeSpan.FromMilliseconds(100));

....

cts.Task.WaitAsync(CancellationToken.None);

Alternative Designs

No response

Risks

No response

Activity

  1. added
    api-suggestion
    on Apr 20, 2023
  2. ghost added
    untriaged
    on Apr 20, 2023
  3. removed
    untriaged
    on Apr 20, 2023
  4. added this to the 8.0.0 milestone on Apr 20, 2023
  5. self-assigned this
    on Apr 20, 2023
  6. tarekgh commented on Apr 20, 2023

    @tarekgh
    MemberAuthor
  7. added
    api-ready-for-review
    blocking
    and removed
    api-suggestion
    on Apr 20, 2023
  8. changed the title [-][API Proposal]: [/-] [+][API Proposal]: Introduce TimeProvider extension method to create a CTS to be cancelled after a specified time period.[/+] on Apr 20, 2023
  9. tarekgh commented on Apr 20, 2023

    @tarekgh
    MemberAuthor
  10. bartonjs commented on Apr 20, 2023

    @bartonjs
    Member

    Video

    On the basis that this is only provided in the Microsoft.Bcl.TimeProvider compat-package, and that TimeProviderTaskExtensions already exists, this looks good as proposed.

    namespace System.Threading.Tasks
    {
        public static partial class TimeProviderTaskExtensions
        {
    
            /// <summary>Initializes a new instance of the <see cref="CancellationTokenSource"/> class that will be canceled after the specified <see cref="TimeSpan"/>. </summary>
            /// <param name="timeProvider">The <see cref="TimeProvider"/> with which to interpret the <paramref name="delay"/>. </param>
            /// <param name="delay">The time interval to wait before canceling this <see cref="CancellationTokenSource"/>. </param>
            /// <exception cref="ArgumentOutOfRangeException"><paramref name="delay"/>'s <see cref="TimeSpan.TotalMilliseconds"/> is less than -1 or greater than <see cref="uint.MaxValue"/> - 1. </exception>
            /// <remarks>
            /// The countdown for the delay starts during the call to the constructor.  When the delay expires,
            /// the constructed <see cref="CancellationTokenSource"/> is canceled if it has
            /// not been canceled already. Subsequent calls to CancelAfter will reset the delay for the constructed
            /// <see cref="CancellationTokenSource"/> if it has not been canceled already.
            /// </remarks>
            public static CancellationTokenSource CreateCancellationTokenSource(this TimeProvider timeProvider, TimeSpan delay) ;
        }
    }
  11. added
    api-approved
    and removed
    blocking
    api-ready-for-review
    on Apr 20, 2023
  12. ghost added
    in-pr
    on Apr 20, 2023
  13. ghost removed
    in-pr
    on Apr 24, 2023
  14. egil commented on Apr 26, 2023

    @egil

    @tarekgh I know this is closed, but wonder if you considered the following extension method as an alternative?

    /// <summary>
    /// Schedules a Cancel operation on the <paramref name="cancellationTokenSource"/>.
    /// </summary>
    /// <param name="cancellationTokenSource">
    /// The <see cref="CancellationTokenSource"/> to cancel after the specified delay.
    /// </param>
    /// <param name="delay">The time span to wait before canceling the <paramref name="cancellationTokenSource"/>.
    /// </param>
    /// <param name="timeProvider">
    /// The <see cref="TimeProvider"/> to use for scheduling the cancellation.
    /// </param>
    /// <exception cref="ObjectDisposedException">The exception thrown when the <paramref name="cancellationTokenSource"/>
    /// has been disposed.
    /// </exception>
    /// <exception cref="ArgumentOutOfRangeException">
    /// The <paramref name="delay"/> is less than -1 or greater than maximum allowed timer duration.
    /// </exception>
    /// <exception cref="ArgumentNullException">The <paramref name="cancellationTokenSource"/> is null.</exception>
    /// <remarks>
    /// <para>
    /// The countdown for the delay starts during this call. When the delay expires,
    /// the <paramref name="cancellationTokenSource"/> is canceled, if it has
    /// not been canceled already.
    /// </para>
    /// <para>
    /// Subsequent calls to CancelAfter will reset the delay for the
    /// <paramref name="cancellationTokenSource"/>, if it has not been canceled already.
    /// </para>
    /// </remarks>
    public static void CancelAfter(this CancellationTokenSource cancellationTokenSource, TimeSpan delay, TimeProvider timeProvider);
  15. tarekgh commented on Apr 26, 2023

    @tarekgh
    MemberAuthor

    @egil you may review the detailed comment #36617 (comment) why we are trying to avoid CancelAfter.

  16. egil commented on Apr 26, 2023

    @egil

    Thanks for the link.

  17. ghost locked as resolved and limited conversation to collaborators on May 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.DateTime

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions