Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task event or action on cancel token requested

This is my code:

public sealed class ProcessingTask : ProcessingObject
{
    private CancellationTokenSource _cancelToken;    
    private int _timeOut = 10000;

    public int ProcessObjectID { get; private set; }       
    public Task ProcessObjectTask { get; private set; }
    public QueueObject queueObject { private get; set; }
    public ProcessingTask(int processObjectID, Uri url)
        : base(url)
    {           
        this.ProcessObjectID = processObjectID;            
    }

    public void ResetTask()
    {
        _cancelToken = new CancellationTokenSource(_timeOut);            
        ProcessObjectTask = new Task(() => DoTaskWork(), _cancelToken.Token);
    }

    private void DoTaskWork()
    {
        Console.WriteLine("Thread {0} was started...", ProcessObjectID);
        //
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);   // imitate hard process
        HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //  

        response.Dispose();
        //

        // Your logic here
        //queueObject.QueueObjectId - dequeud object is available here
        //
        if (_cancelToken.IsCancellationRequested)
        {
            Console.WriteLine("Thread {0} was timed out...", ProcessObjectID);                
        }
        else
        {
            Console.WriteLine("Thread {0} was finished...", ProcessObjectID);
        }
    }
}

I wonder if exists any way to use event (or some action) if CancellationRequested. I mean that I need to do SomeMethod() exactly in the moment when _timeout Expired. Can anyone explain me: is it possible in general?

like image 517
Alexander Avatar asked Oct 02 '15 08:10

Alexander


People also ask

How do you handle a cancellation token?

The wait handle of the cancellation token will become signaled in response to a cancellation request, and the method can use the return value of the WaitAny method to determine whether it was the cancellation token that signaled. The operation can then just exit, or throw a OperationCanceledException, as appropriate.

How does a cancellation token work?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.

Should cancellation token source be disposed?

Always call Dispose before you release your last reference to the CancellationTokenSource. Otherwise, the resources it is using will not be freed until the garbage collector calls the CancellationTokenSource object's Finalize method.

What is the way to create a task that can be Cancelled after it starts?

Create and start a cancelable task. Pass a cancellation token to your user delegate and optionally to the task instance. Notice and respond to the cancellation request in your user delegate. Optionally notice on the calling thread that the task was canceled.


1 Answers

You're looking for CancellationToken.Register:

Registers a delegate that will be called when this CancellationToken is canceled.

Register an action like this:

_cancelToken.Token.Register(() => DoStuff());
like image 178
Yuval Itzchakov Avatar answered Sep 28 '22 18:09

Yuval Itzchakov