.NET Core 2.0遷移技巧之MemoryCache問題修複

來源:互聯網
上載者:User

標籤:void   技術   runtime   amp   new   div   object   ges   eval   

對於傳統的.NET Framework項目而言,System.Runtime.Caching命名空間是常用的工具了,其中MemoryCache類則常被用於實現記憶體緩衝。

.NET Core 2.0暫時還不支援System.Runtime.Caching dll,這也就意味著MemoryCache相關代碼不再起作用了。

但是好訊息是,我們可以使用.NET Core 2.0的新API實現記憶體緩衝功能,簡單修改代碼,解決不相容問題。

 

解決方案

 

  1.將舊代碼匯入項目中,如下:

 

using System;using System.Runtime.Caching;namespace TestWebApp.Service{    public class MemoryCacheService    {        static ObjectCache cache = MemoryCache.Default;        /// <summary>        /// 擷取緩衝值        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        private object GetCacheValue(string key)        {            if (key != null && cache.Contains(key))            {                return cache[key];            }            return default(object);        }        /// <summary>        /// 添加緩衝內容        /// </summary>        /// <param name="key"></param>        /// <param name="value"></param>        public static void SetChacheValue(string key, object value)        {            if (key != null)            {                CacheItemPolicy policy = new CacheItemPolicy                {                    SlidingExpiration = TimeSpan.FromHours(1)                                    };                cache.Set(key, value, policy);            }        }    }}

 

  匯入後你會發現VS會提示無法找到System.Runtime.Caching命名空間,原有的代碼無法直接編譯使用。

 

  2.添加對 Microsoft.Extensions.Caching.Memory命名空間的引用,它提供了.NET Core預設實現的 MemoryCache類,以及全新的記憶體緩衝API

  

using Microsoft.Extensions.Caching.Memory;

 

  3.改寫代碼,使用新的API實現記憶體緩衝功能

  初始化緩衝對象方式改寫前:

static ObjectCache cache = MemoryCache.Default;

 

  初始化緩衝對象方式改寫後:

static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());

 

  讀取記憶體緩衝值方式變化:

private object GetCacheValue(string key){    if (key != null && cache.Contains(key))    {        return cache[key];    }    return default(object);}

 

  改寫後:

private object GetCacheValue(string key){    object val = null;    if (key != null && cache.TryGetValue(key, out val))    {        return val;    }    else    {        return default(object);    }}

 

  設定記憶體緩衝內容方式變化:

public static void SetChacheValue(string key, object value){    if (key != null)    {        CacheItemPolicy policy = new CacheItemPolicy        {            SlidingExpiration = TimeSpan.FromHours(1)        };        cache.Set(key, value, policy);    }}

 

  修改後:

 public static void SetChacheValue(string key, object value){    if (key != null)    {        cache.Set(key, value, new MemoryCacheEntryOptions        {            SlidingExpiration = TimeSpan.FromHours(1)        });    }}

 

結論 

在使用了Microsoft.Extensions.Caching.Memory下的新API改寫了舊代碼後,你會發現原有的各種記憶體緩衝逾時策略全都是有對應新API的,包括AbsoluteExpiration, SlidingExpiration等等。

所以我們還是可以很輕鬆的使用.NET Core新API簡單改動下下就能重用現有絕大部分舊代碼,將其遷移過來繼續起作用。

 

遷移後的完整代碼如下:

using Microsoft.Extensions.Caching.Memory;using System;namespace TestMemoryCacheWebApp.Services{    public class MemoryCacheService    {        static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());        /// <summary>        /// 擷取緩衝值        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        private object GetCacheValue(string key)        {            object val = null;            if (key != null && cache.TryGetValue(key, out val))            {                return val;            }            else            {                return default(object);            }        }        /// <summary>        /// 添加緩衝內容        /// </summary>        /// <param name="key"></param>        /// <param name="value"></param>        public static void SetChacheValue(string key, object value)        {            if (key != null)            {                cache.Set(key, value, new MemoryCacheEntryOptions                {                    SlidingExpiration = TimeSpan.FromHours(1)                });            }        }    }}

 

.NET Core 2.0遷移技巧之MemoryCache問題修複

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.