1

セッションの実装を作成しようとしています。それを完了するには、セッション タイムアウトを作成する必要があります。これを行うには、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これにより、Timer オブジェクトにアクセスできるようになりますが、refreshSession()「再スケジュール」する方法がわかりません。

  2. SessioninabandonSession()コールバックへの参照を取得する方法はまだわかりません 。Sessionでオブジェクトを送信する方法はありstateInfoますか?

オブジェクトにへの参照を保存し、呼び出しのためにオブジェクトのメソッドをコールバックに参照させることができると考えていSessionManagerました。ずさんに見えたけど。どう思いますか?SessionSessionabandonSession()

追加情報が必要な場合はお知らせください。

4

1 に答える 1

1

Change メソッドを使用して、新しい呼び出し遅延を設定します。

sessionTimer.Change(timeToLive, timeToLive)

コールバック メソッドで値を取得する場合、現在nullとして渡す 2 番目のパラメーターはコールバック オブジェクトです...タイマー コールバック メソッドは署名を強制し、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 に答える