c# - .NET Core 中有 CallContext.GetData / SetData 的实现吗?
问题描述
AsyncLocal<>
在 .NET Core 中,例如CallContext.LogicGetData
/ LogicSetData
。GetData
和怎么样SetData
?
Thread.GetData/SetData
, ThreadStatic
,ThreadLocal
所有这些都有相同的问题,当Thread
完成时,这些值不会被清除,如果这些Thread
重用(或者可能Thread Id
重用),则LocalValue已经存在。
class Program
{
[ThreadStatic]
private static string Static;
private static ThreadLocal<string> Local = new ThreadLocal<string>(false);
private static LocalDataStoreSlot Slot = Thread.AllocateDataSlot();
static void Main(string[] args)
{
var threadIds = new List<int>();
for (var i = 0; i < 100; i++)
{
Task.Run(() =>
{
if (threadIds.Contains(Thread.CurrentThread.ManagedThreadId))
{
if(Static == null || Local.Value == null || Thread.GetData(Slot) == null)
{
// never get in
}
else
{
// same thread id always already exists value
}
}
else
{
threadIds.Add(Thread.CurrentThread.ManagedThreadId);
if (Static == null && Local.Value == null && Thread.GetData(Slot) == null)
{
var threadId = Thread.CurrentThread.ManagedThreadId.ToString();
Static = threadId;
Local.Value = threadId;
Thread.SetData(Slot, threadId);
}
else
{
//never get in
}
}
}).Wait();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
我知道怎么CallContext
做,它只是将LogicalCallContext
值复制到子线程而不复制IllogicalCallContext
. 但是 .NET Core 只IAsyncLocalValueMap
在.NET Core 中ExecutionContext
,它总是复制到子线程(SuppressFlow 除外)。那么,有没有GetData
/的实现SetData
?或完成后的任何清洁方式ThreadLocal
。
解决方案
使用 AsyncLocal 的更改处理程序在线程更改时清除值?
private static AsyncLocal<string> AsyncLocal
= new AsyncLocal<string>(ThreadContextChanged);
private static void ThreadContextChanged(AsyncLocalValueChangedArgs<string> changedArgs)
{
if (changedArgs.ThreadContextChanged &&
changedArgs.CurrentValue != null)
{
AsyncLocal.Value = null;
}
}
推荐阅读
- vue.js - Laravel Mix 代码拆分在 Safari 中被破坏
- html - 如何在移动视图中更改 Bootstrap 导航栏父菜单项图标的位置?
- go - GoLang 中的数学/兰德
- asp.net-core - 为什么我的原点在 asp net core 3 中为空,而不是 localhost
- javascript - CORS BLOCKED 'Access-Control-Allow-Origin' Firebase 功能不允许
- javascript - Three.js - 用线条连接粒子 - 如何更高效?
- django - 如何在Django中测试一个实例是否有一个ForeignKey指向它的子类?
- mysql - Django 我想传递多个 id 并获取他们的数据。场景:社交网络系统
- ios - 即使方向被锁定,我如何检测设备方向
- sql - 更改现有数据的序列号列