2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

一定時間経過したらアクセスできなくなるキャッシュを使う (C#)

Last updated at Posted at 2020-04-20

一定時間経過したらアクセスできなくなるデータキャッシュを使う (C#)

# 以下の記事が書かれた時の版数は .NET Core 3.1 (3.1.201), System.Runtime.Caching 4.7.0 となります.

外部リソースから拾ってきたデータをキャッシュしたい場合、ずっとキャッシュすると外部リソース側が更新されたときに困る. そういう時とかに使えるデータキャッシュ. 以前はそういう用途が多い Web アプリケーション用に ASP.NET だけそういう機能があったが、今はデスクトップアプリでも普通に使えるようになった. 最後にアクセスしてから一定時間経過後にキャッシュを無効化したいのであれば AbsoluteExpiration の代わりに SlidingExpiration を使う.

とりあえず今回は有効期間1分で、10秒ごとにアクセスしてみた.

using System;
using System.Runtime.Caching;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static readonly ObjectCache Cache = MemoryCache.Default;

        static void Main(string[] args)
        {
            while (true)
            {
                var message = (string)Cache["test"];
                if (message == null)
                {
                    message = $"cached at {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
                    Cache.Add("test", message, new CacheItemPolicy()
                    {
                        AbsoluteExpiration = DateTime.Now.AddMinutes(1)
                    });
                }
                Console.WriteLine(message);
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
    }
}

なお、System.Runtime.Caching 使用時には Install-Package System.Runtime.Caching で nuget からインストールする必要がある、念の為.

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?