AsyncLocal<T>我读到MSDN 文档中读到了相关内容,但有一点我仍然不清楚。
我正在研究诸如上下文绑定的缓存/记忆之类的东西,其目的很简单,就是跨逻辑请求存储数据。这与旧的类似HttpContext.Current,数据跨请求存储,并在请求结束时释放。然而,就我而言,我希望与环境无关,因此实现不受 ASP.NET MVC、ASP.NET Core、WCF 等的约束,同时仍然能够存储和检索数据绑定到逻辑请求,而不在逻辑上不同的请求之间共享它。
为了根据问题简化我的代码,它看起来有点像这样:
\n\nclass ContextualStorageAccessor\n{\n // ConcurrentDictionary since it\'s okay if some parallel operations are used per logical request \n private readonly AsyncLocal<ConcurrentDictionary<string, object>> _csm = new AsyncLocal<ConcurrentDictionary<string, object>>();\n\n public ConcurrentDictionary<string, object> Storage\n { \n get\n {\n if (_csm.Value != null)\n return _csm.Value;\n\n _csm.Value = new ConcurrentDictionary<string, object>();\n\n return _csm.Value;\n }\n } \n}\nRun Code Online (Sandbox Code Playgroud)\n\n的生命周期ContextualStorageAccessor是单例的。
现在的问题是:Value每个请求都会有一个唯一的实例吗?换句话说,我是否需要继续分配默认值_csm.Value手动分配默认值?或者我可以依靠应用程序本身的类型(例如,ASP.NET MVC、WCF 等)来处理它?
或者,换句话来说:“异步流”的结尾在哪里,并保证 …
I'm working on something like a context-bound caching and a little bit stuck on thread-safety...
Let's say I have the following code:
public class AsynLocalContextualCacheAccessor : IContextualCacheAccessor
{
private static readonly AsyncLocal<CacheScopesManager> _rCacheContextManager = new AsyncLocal<CacheScopesManager>();
public AsynLocalContextualCacheAccessor()
{
}
public CacheScope Current
{
get
{
if (_rCacheContextManager.Value == null)
_rCacheContextManager.Value = new CacheScopesManager();
return _rCacheContextManager.Value.Current;
}
}
}
public class CacheScopesManager
{
private static readonly AsyncLocal<ImmutableStack<CacheScope>> _scopesStack = new AsyncLocal<ImmutableStack<CacheScope>>(OnValueChanged);
public CacheScopesManager()
{
CacheScope contextualCache = _NewScope();
_scopesStack.Value = …Run Code Online (Sandbox Code Playgroud)