如何重新安排C#System.Threading.Timer?

时间:2013-06-13 18:59:44

标签: c# timer .net-4.5

我正在尝试创建一个Session实现。为了完成它,我需要创建会话超时。为此,我决定使用在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()中的Timer对象但是我 不知道如何“重新安排”它。

  2. 我仍然不知道如何获得对它的引用 Session回调中的abandonSession()。有没有办法在Session

  3. 中发送stateInfo对象

    我原以为我可以在SessionManager对象上存储对Session的引用,并在Session对象的abandonSession()对象上使用回调引用方法。这看起来很草率。你觉得怎么样?

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

1 个答案:

答案 0 :(得分:1)

使用 Change method 设置新的调用延迟:

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?
}