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?
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With