在非asp.net程序中使用缓存

下面是一个控制台的例子,在.net remoting,wcf等分布式程序的中间层也可以这样使用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Web;

namespace ConsoleApplication1
{

    class CacheExample
    {
        public CacheExample()
        {

        }

        public string GetString()
        {
            Cache cache = HttpRuntime.Cache;
            if (cache["string_key"] == null)
            {
                Console.WriteLine("cache it");

                cache["string_key"] = "23333333333333333";

                return cache["string_key"].ToString();

            }
            else
            {
                Console.WriteLine("from cache");
                return cache["string_key"].ToString();
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i ++)
            {
               Console.WriteLine( new CacheExample().GetString());
            }
        }
    }
}

你可能感兴趣的:(asp.net)