4

Addメソッドがすでに存在する場合は失敗することをどこでも読んだことがありますが、例外をスローしますか、それともサイレントに失敗しますか?

まだ存在していないはずのマルチスレッドWebアプリケーションを作成していますが、キャッシュを上書きすると問題が発生するため、Insertメソッドを使用できません。

これは私にできることでしょうか:

try
{
    HttpContext.Current.Cache.Add("notifications", notifications, null,
      System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(8),
      System.Web.Caching.CacheItemPriority.High, null);
}
catch
{
    //do whatever if notifications already exist
}

答えてくれてありがとう:)

4

3 に答える 3

0

これは自分でテストするのは簡単ですが、エラーがスローされます。使用するのに適したユーティリティ関数:

    /// <summary>
    /// Places an item into the cache using absolute expiration.
    /// </summary>
    /// <param name="key">Key of the item being inserted</param>
    /// <param name="item">Item to insert</param>
    /// <param name="expireTime">Absolute expiration time of the item</param>
    public static void InsertIntoCacheAbsoluteExpiration(string key, object item, DateTime expireTime)
    {
        if (HttpContext.Current == null)
        {
            return;
        }

        lock (LOCK)
        {
            HttpRuntime.Cache.Remove(key);
            HttpRuntime.Cache.Add(
                key,
                item,
                null,
                expireTime,
                System.Web.Caching.Cache.NoSlidingExpiration,
                System.Web.Caching.CacheItemPriority.Normal,
                null);
        }
    }

キーが存在しない場合、Remove は文句を言いません。キーが既に存在するかどうかをテストしたい場合は、いつでも確認できます

HttpRuntime.Cache.Get(key) != null

ロック変数を使用している限り、チェックで何かがキャッシュにないことが示され、チェックと追加の間に表示されるという問題に遭遇することはありません。

于 2012-07-11T12:24:50.353 に答える