I'm no too good with async processes in C#. I need to implement method, that can be called multiple times by async requests, but request data and serve response once. I've created this method, inspired by common JS promise pattern:
private Task<bool> DoSomething(string key)
{
// generating unique key
string cacheKey = "do-comething-" + key;
// searching cache for a Task in progress
var cachedRequest = MemoryCache.Default.Get(cacheKey, null) as Task<bool>;
// if found - return old Task
if (cachedRequest != null)
{
return cachedRequest;
}
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
CacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(60))
};
// storing Task object in cache
MemoryCache.Default.Set(cacheKey, tcs.Task, cip);
try
{
// do something long here
tcs.TrySetResult(true);
}
catch(Exception ex)
{
tcs.TrySetResult(false);
}
finally
{
MemoryCache.Default.Remove(cacheKey);
}
return tcs.Task;
}
Is it ok, or I'm totally out of it? Any advice will be highly appreciated. Thanks.