请求取消令牌的任务事件或操作
这是我的代码:
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()。 任何人都可以解释一下:一般来说可能吗?
您正在寻找CancellationToken.Register
:
注册取消取消取消时将调用的委托。
注册这样的动作:
上述就是C#学习教程:请求取消令牌的任务事件或操作分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
_cancelToken.Token.Register(() => DoStuff());
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1021801.html