这是我的代码:
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);
}
}
}
我想知道如果使用CancellationRequested,是否存在使用事件(或某些操作)的任何方法。我的意思是我需要在_timeout Expired时完全执行SomeMethod()。任何人都可以解释一下:一般来说可能吗?
答案 0 :(得分:12)
您正在寻找CancellationToken.Register
:
注册取消此CancellationToken时将被调用的委托。
注册这样的行动:
_cancelToken.Token.Register(() => DoStuff());