Task event or action on cancel token requested

2019-02-24 06:44发布

问题:

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?

回答1:

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());