CancellationToken and CancellationTokenSource-How to use it?

后端 未结 3 2007
北荒
北荒 2021-01-02 12:23

I have a UI button called Load. It spawns a thread, which in turn spawns a task. There is a wait on the task, and if it expires the task gets cancelled. The Load button is n

3条回答
  •  一向
    一向 (楼主)
    2021-01-02 12:47

    First, if you are using Visual Studio 2012+ you can add the Microsoft.Bcl.Async package to add support for async and other advanced functionality to your .NET 4.0 project.

    If you are using Visual Studio 2010, you can use the WithTimeout extension method that comes with the ParallelExtensionsExtras library. The method wraps the original Task with a TaskCompletionSource and a timer that calls SetCancelled if it expires.

    The code is here but the actual method is simple:

        /// Creates a new Task that mirrors the supplied task but that 
        /// will be canceled after the specified timeout.
        /// Specifies the type of data contained in the 
        /// task.
        /// The task.
        /// The timeout.
        /// The new Task that may time out.
        public static Task WithTimeout(this Task task, 
                                                              TimeSpan timeout)
        {
            var result = new TaskCompletionSource(task.AsyncState);
            var timer = new Timer(state => 
                            ((TaskCompletionSource)state).TrySetCanceled(),
                            result, timeout, TimeSpan.FromMilliseconds(-1));
            task.ContinueWith(t =>
            {
                timer.Dispose();
                result.TrySetFromTask(t);
            }, TaskContinuationOptions.ExecuteSynchronously);
            return result.Task;
        }
    

    You can use it right after creating your task:

    var myTask=Task.Factory.StartNew(()=>{...})
               .WithTimeout(TimeSpan.FromSeconds(20));
    

    In general, you can create the behaviour you want by creating a TaskCompletionSource calling its SetResult, SetCancelled methods in response to the events or criteria you set.

提交回复
热议问题