gpt4 book ai didi

c# - 请求取消 token 的任务事件或操作

转载 作者:太空狗 更新时间:2023-10-30 00:10:10 24 4
gpt4 key购买 nike

这是我的代码:

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

我想知道如果取消请求是否存在任何使用事件(或某些操作)的方法。我的意思是我需要在 _timeout 过期的那一刻准确地执行 SomeMethod() 。任何人都可以向我解释:一般来说有可能吗?

最佳答案

您正在寻找 CancellationToken.Register :

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

像这样注册一个 Action :

_cancelToken.Token.Register(() => DoStuff());

关于c# - 请求取消 token 的任务事件或操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32903487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com