gpt4 book ai didi

c# - .NET Core 中是否有 CallContext.GetData/SetData 的实现?

转载 作者:行者123 更新时间:2023-11-30 16:39:14 25 4
gpt4 key购买 nike

AsyncLocal<>在 .NET Core 中,如 CallContext.LogicGetData/LogicSetData .怎么样GetDataSetData ?
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 IAsyncLocalValueMapExecutionContext ,它总是复制到子线程(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;
}
}

关于c# - .NET Core 中是否有 CallContext.GetData/SetData 的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53406968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com