我正在尝试创建一个 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?
}
}
我需要帮助:
我可以使对象
sessionTimer
的成员Session
。这将使我可以访问 Timer 对象,refreshSession()
但我不知道如何“重新安排”它。我仍然不知道如何获得对
Session
inabandonSession()
回调的引用。有没有办法在 中发送Session
对象stateInfo
?
我在想我可以存储SessionManager
对Session
对象的引用,并让回调引用Session
对象上的方法以进行abandonSession()
调用。不过,这似乎很草率。你怎么看?
请让我知道是否需要其他信息。