search
HomeBackend DevelopmentC#.Net TutorialMemoryCache problem fix solutions

MemoryCache problem fix solutions

Sep 01, 2017 pm 02:32 PM
methodsolve

This article mainly introduces you to the relevant information about .NET Core 2.0 migration tips - MemoryCache problem repair and solution. The article introduces it in detail through sample code, which has certain reference learning value for everyone's study or work. Friends who need it, please follow the editor to learn together.

Preface

Everyone should know that for traditional .NET Framework projects, System.Runtime.CachingNamespace is a commonly used tool, and the MemoryCache class is often used to implement memory caching.

.NET Core 2.0 does not yet support System.Runtime.Caching dll, which means that MemoryCache related code no longer works.

But the good news is that we can use the new API of .NET Core 2.0 to implement the memory cache function and simply modify the code to solve the incompatibility problem. Not much to say below, let’s take a look at the detailed introduction.

Solution

1. Import the old code into the project, as follows:


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);
   }
  }
 }
}

After importing, you will find that VS will prompt that the System.Runtime.Caching namespace cannot be found, and the original code cannot be directly compiled and used.

2. Add a reference to the Microsoft.Extensions.Caching.Memory namespace, which provides the MemoryCache class implemented by .NET Core by default, and Brand new memory cache API


using Microsoft.Extensions.Caching.Memory;

3. Rewrite the code and use the new API to implement the memory cache function

Initialize the cache object method before rewriting:


static ObjectCache cache = MemoryCache.Default;

After rewriting the method of initializing cache objects:


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

Changes in the method of reading memory cache values:


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

After rewriting:


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

Changes in setting the memory cache content method:


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

After modification:


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

Conclusion

After using After the new API under Microsoft.Extensions.Caching.Memory rewrites the old code, you will find that all the original memory cache timeout strategies have corresponding new APIs, including AbsoluteExpiration, SlidingExpiration, etc.

So we can still easily use the new .NET Core API to reuse most of the existing old code with simple changes, and migrate it to continue to work.

The complete code after migration is as follows:


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)
    });
   }
  }
 }
}

The above is the detailed content of MemoryCache problem fix solutions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.