Skip to content

Instantly share code, notes, and snippets.

@ShiroTeky
Last active October 21, 2017 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShiroTeky/8e6cfce1d9b0fd4187e1cc8630cb0efa to your computer and use it in GitHub Desktop.
Save ShiroTeky/8e6cfce1d9b0fd4187e1cc8630cb0efa to your computer and use it in GitHub Desktop.
I share this simple article to show you some code about a TCache async method. I encountered this exception: Unable to convert a async lambda expression in Func.
//lambda async expression in func
//the previows signature was :T Get(string cacheKeyName, int cacheTimeOutSeconds, Func<T> func)
string cacheName = "all-tenants-cache-name";
int cacheTimeOutSeconds = 30;
List<Tenant> tenants =
await new TCacheProvider<List<Tenant>>().Get(
cacheName, cacheTimeOutSeconds,
async () =>{
//here some asynchronous methods
//please return something here
});
using System;
using System.Threading.Tasks;
namespace Custom.TCache.Web
{
public interface ITCache<T>
{
Task<T> Get(string cacheKeyName, int cacheTimeOutSeconds, Func<Task<T>> func);
}
}
using System;
using System.Threading.Tasks;
namespace Custom.TCache.Web
{
public class TCacheProvider<T>
{
public Task<T> Get(string cacheKeyName, int cacheTimeOutSeconds, Func<Task<T>> func)
{
return new TCacheInternal<T>().Get(
cacheKeyName,cacheTimeOutSeconds,func);
}
}
}
using System;
using System.Threading.Tasks;
using System.Web;
namespace Custom.TCache.Web
{
public class TCacheProviderInternal<T> : ITCache<T>
{
internal static readonly object Locker = new object();
public Task<T> Get(string cacheName,int cacheTimeOutSeconds,Func<Task<T>> func)
{
var obj = HttpContext.Current.Cache.Get(cacheName);
if (obj != null)
{
return (Task<T>)obj;
}
lock (Locker)
{
if (obj == null)
{
obj = func();
HttpContext.Current.Cache.Insert(cacheName, obj, null,
DateTime.Now.Add(new TimeSpan(0, 0, cacheTimeOutSeconds)),
TimeSpan.Zero);
}
return (Task<T>)obj;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment