text stringlengths 0 13.4k |
|---|
Chapter 22: |
System.Runtime.Caching.MemoryCache |
(ObjectCache) |
Section 22.1: Adding Item to Cache (Set) |
Set function inserts a cache entry into the cache by using a CacheItem instance to supply the key and value for the |
cache entry. |
This function Overrides ObjectCache.Set(CacheItem, CacheItemPolicy) |
private static bool SetToCache() |
{ |
string key = "Cache_Key"; |
string value = "Cache_Value"; |
//Get a reference to the default MemoryCache instance. |
var cacheContainer = MemoryCache.Default; |
var policy = new CacheItemPolicy() |
{ |
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(DEFAULT_CACHE_EXPIRATION_MINUTES) |
}; |
var itemToCache = new CacheItem(key, value); //Value is of type object. |
cacheContainer.Set(itemToCache, policy); |
} |
Section 22.2: System.Runtime.Caching.MemoryCache |
(ObjectCache) |
This function gets existing item form cache, and if the item don't exist in cache, it will fetch item based on the |
valueFetchFactory function. |
public static TValue GetExistingOrAdd<TValue>(string key, double minutesForExpiration, |
Func<TValue> valueFetchFactory) |
{ |
try |
{ |
//The Lazy class provides Lazy initialization which will evaluate |
//the valueFetchFactory only if item is not in the cache. |
var newValue = new Lazy<TValue>(valueFetchFactory); |
//Setup the cache policy if item will be saved back to cache. |
CacheItemPolicy policy = new CacheItemPolicy() |
{ |
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesForExpiration) |
}; |
//returns existing item form cache or add the new value if it does not exist. |
var cachedItem = _cacheContainer.AddOrGetExisting(key, newValue, policy) as |
Lazy<TValue>; |
return (cachedItem ?? newValue).Value; |
} |
catch (Exception excep) |
{ |
GoalKicker.com – .NET Framework Notes for Professionals |
81 |
return default(TValue); |
} |
} |
GoalKicker.com – .NET Framework Notes for Professionals |
82 |
Chapter 23: System.Reflection.Emit |
namespace |
Section 23.1: Creating an assembly dynamically |
using System; |
using System.Reflection; |
using System.Reflection.Emit; |
class DemoAssemblyBuilder |
{ |
public static void Main() |
{ |
// An assembly consists of one or more modules, each of which |
// contains zero or more types. This code creates a single-module |
// assembly, the most common case. The module contains one type, |
// named "MyDynamicType", that has a private field, a property |
// that gets and sets the private field, constructors that |
// initialize the private field, and a method that multiplies |
// a user-supplied number by the private field value and returns |
// the result. In C# the type might look like this: |
/* |
public class MyDynamicType |
{ |
private int m_number; |
public MyDynamicType() : this(42) {} |
public MyDynamicType(int initNumber) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.