C
C#8mo ago
nox7

Mutex? ASP Core - Only Allowing a Method to Be Run One at a Time

I have a scenario where I want all requests to an endpoint to have the ability to only be run one at a time. This method is asynchronous. The situation: When a client of ours logs into their dashboard, it shows a "marketing tips" blog section which pulls blog articles from a 3rd party. However, I don't need every request to hit the 3rd party list API for those articles - every client will see the same article. I want the HTTP request to list and cache those articles to only ever be running one at a time. In essence - If blogs need to be fetched from third party, do not let other processes run this request - Else, let processes run this request as often as they want (it will get the blogs from a local cache in this case) Will a Mutex work for this case?
1 Reply
nox7
nox7OP8mo ago
This is an example of what I am thinking to do for a service method, but am not sure if this is a proper Mutex implementation - because of the asynchronous access to Redis
public async Task GetBlogArticles()
{
var redis = RedisProvider.GetConnectionNotNull();
var redisDb = redis.GetDatabase();

string cacheKey = "client:dashboard:blog-articles";
var cachedBlogsRedisValue = await redisDb.StringGetAsync(cacheKey);
if (!cachedBlogsRedisValue.HasValue)
{
// Needs to be cached, lock mutex and fetch from API
FootbridgeBlogFetchMutex.WaitOne();
}
else
{
// No mutex lock needed, continue
}
}
public async Task GetBlogArticles()
{
var redis = RedisProvider.GetConnectionNotNull();
var redisDb = redis.GetDatabase();

string cacheKey = "client:dashboard:blog-articles";
var cachedBlogsRedisValue = await redisDb.StringGetAsync(cacheKey);
if (!cachedBlogsRedisValue.HasValue)
{
// Needs to be cached, lock mutex and fetch from API
FootbridgeBlogFetchMutex.WaitOne();
}
else
{
// No mutex lock needed, continue
}
}
Though, now I am starting to think to just store a Task object as a static method of the service class object and have any future calls await that task if it exists...
Want results from more Discord servers?
Add your server