如何重新调度c# System.Threading.Timer

本文关键字:Threading Timer System 何重新 调度 | 更新日期: 2023-09-27 18:18:22

我正在尝试创建一个会话实现。为了完成它,我需要创建会话超时。为此,我决定使用一个在x秒后执行的Timer。但是,如果在计时器到期之前收到请求,则应该重新调度。

我有一个定时器:

using System.Threading.Timer;
public class SessionManager {
    private int timeToLive; //Initialized in the constructor.
    private ConcurrentDictionary<Guid, Session> sessions; //Populated in establishSession. Removed in abandonSession.
    public Session establishSession(...)
    {
        Session session = ...; //I have a session object here. It's been added to the dictionary.
        TimerCallback tcb = abandonSession;
        Timer sessionTimer = new Timer(tcb, null, timeToLive, Timeout.Infinite);
    }
    public void abandonSession(Object stateInfo)
    {
        //I need to cancel the session here, which means I need to retrieve the Session, but how?
    }
    public void refreshSession(Session session)
    {
        //A request has come in; I have the session object, now I need to reschedule its timer. How can I get reference to the timer? How can I reschedule it?
    }
}

我需要什么帮助:

  1. 我可以使sessionTimer成为Session对象的成员。那会给我访问定时器对象在refreshSession(),但我我不知道如何"重新安排"它。

  2. 我仍然不知道如何获得对abandonSession()回调中的Session。在stateInfo中是否有发送Session对象的方法?

我想我可以在Session对象上存储对SessionManager的引用,并让回调引用Session对象上的abandonSession()调用的方法。不过这看起来很草率。你觉得呢?

如何重新调度c# System.Threading.Timer

如果需要更多的信息,请告诉我。

使用Change方法设置新的调用延迟:

sessionTimer.Change(timeToLive, timeToLive)

至于在回调方法中获取值,您当前作为null传递的第二个参数是您的回调对象…你的Timer回调方法强制object的签名,你可以将该对象强制转换为你传入的类型来使用它。

var myState = new Something();
var sessionTimer = new Timer(tcb, myState, timeToLive, Timeout.Infinite);
...
public void abandonSession(Object stateInfo)
{
    var myState = (Something)stateInfo;
    //I need to cancel the session here, which means I need to retrieve the Session, but how?
}