1

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

所以,我有一个计时器:

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。这将使我可以访问 Timer 对象,refreshSession()但我不知道如何“重新安排”它。

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

我在想我可以存储SessionManagerSession对象的引用,并让回调引用Session对象上的方法以进行abandonSession()调用。不过,这似乎很草率。你怎么看?

请让我知道是否需要其他信息。

4

1 回答 1

1

使用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?
}
于 2013-06-13T19:07:42.063 回答