task timeout c# code example

Example: task with timeout c#

/// <summary>/// Run an action and kill it when canceling the token/// </summary>/// <param name="action">The action to execute</param>/// <param name="token">The token</param>/// <param name="waitForGracefulTermination">If set, the task will be killed with delay so as to allow the action to end gracefully</param>private static Task RunCancellable(Action action, CancellationToken token, TimeSpan? waitForGracefulTermination=null){    // we need a thread, because Tasks cannot be forcefully stopped    var thread = new Thread(new ThreadStart(action));    // we hold the reference to the task so we can check its state    Task task = null;    task = Task.Run(() =>    {        // task monitoring the token        Task.Run(() =>        {            // wait for the token to be canceled            token.WaitHandle.WaitOne();            // if we wanted graceful termination we wait            // in this case, action needs to know about the token as well and handle the cancellation itself            if (waitForGracefulTermination != null)            {                Thread.Sleep(waitForGracefulTermination.Value);            }            // if the task has not ended, we kill the thread            if (!task.IsCompleted)            {                thread.Abort();            }        });        // simply start the thread (and the action)        thread.Start();        // and wait for it to end so we return to the current thread        thread.Join();        // throw exception if the token was canceled        // this will not be reached unless the thread completes or is aborted        token.ThrowIfCancellationRequested();    }, token);    return task;}