更新时间:2022-11-08 23:18:26
由于是并行的,因此您马上就可能需要使用System.Collections.Concurrent
,并且由于需要键/值查找(用户标识符/HTTP响应),您需要一个ConcurrentDictionary.而且,由于所有用户都有一个公共缓存,因此您需要将其存储在一个静态变量中,该变量可用于所有线程和所有HTTP请求.
Since it's parallel, you know right away you're probably going to need to use System.Collections.Concurrent
, and since you need key/value lookup (user identifier/HTTP response) you need a ConcurrentDictionary. And since there is a common cache for all users, you will want to store it in a static variable, which is available to all threads and all HTTP requests.
这是一个简单的例子:
public class MyCacheClass
{
//Store the list of users/requests
static private ConcurrentDictionary<string, Task<HttpResponseMessage>> _cache = new ConcurrentDictionary<string, Task<HttpResponseMessage>>();
//Get from the ConcurrentDictionary or add if it's not there
public async Task<HttpResponseMessage> GetUser(string key)
{
return await _cache.GetOrAdd(key, GetResponse(key));
}
//You just to implement this method, potentially in a subclass, to get the data
protected virtual async Task<HttpResponseMessage> GetResponse(string key)
{
var httpClient = new HttpClient();
var url = string.Format(@"http://www.google.com?q={0}", key);
return await httpClient.GetAsync(url);
}
}
然后获取用户信息,只需致电:
Then to get a user's information, just call:
var o = new MyCacheClass();
var userInfo = await o.GetUser(userID);
注意:如果要在生产系统上使用这样的代码,则可以考虑在一段时间或达到一定大小后添加一些清除或修整缓存的方法.否则,您的解决方案可能无法按需要扩展.
Note: If you're going to use code like this on a production system, you might consider adding some means of purging or trimming the cache after a period of time or when it reaches a certain size. Otherwise your solution may not scale the way you need it to.