1

I have a variable (custom object) in a singleton that I want to update based on a timer.

So, every 30 minutes I would get the new values from the database and update this variable. Eventual consistency between various servers is the only thing that's important - so if one server has a bit older value because the singleton timer is not synced that isn't an issue.

I was thinking of spawning off a thread in the singleton constructor with a timer and updating the variable based on that timer.

I'm not sure where in the application lifecycle a thread started from a singleton could be terminated. Is this the correct architectural approach to this? Or, is there something else I should be doing?

4

2 に答える 2

3

これは一見簡単そうに見えるかもしれませんが、ASP.NET で繰り返しバックグラウンド タスクを処理することは推奨されていないため、非常に複雑なタスクになる可能性があります。その理由は、サイトでの非アクティブ期間、一部の CPU/メモリのしきい値に達した場合など、制御できない特定の状況で、アプリケーション ドメインが Web サーバーによってアンロードされる可能性があるためです。もちろん、アプリケーションがメモリからアンロードすると、このバックグラウンド タスクを実行するために生成したすべてのスレッドが単純に停止します。

または、他にやるべきことがありますか?

はい、達成しようとしていることに応じて、おそらく他のアプローチがあります(この変数が必要な場所と理由、および使用方法など)。

于 2012-02-12T08:21:54.853 に答える
0

期限切れになったら、要求されたときに更新しないのはなぜですか? これにより、使用されていない場合に更新に時間を無駄にすることはありません。このような...

public class MyClass
{
    private static MyClass sInstance
    private static DateTime sInstanceLastUpdated = DateTime.MinValue;
    public static MyClass Instance
    {
        get
        {
            if(sInstance == null || DateTime.Now.Subtract(sInstanceLastUpdated).TotalMinutes > 30)
            {
                sInstance = new MyClass();
                // initialize.
            }
            return sInstance;
        }
    }
}
于 2012-02-12T04:46:06.337 に答える