gpt4 book ai didi

c# - 托管线程是否可能与自身存在竞争条件

转载 作者:行者123 更新时间:2023-11-30 22:06:17 25 4
gpt4 key购买 nike

因此,为了让程序运行的每个线程都有一个单独的上下文,我设置了一个上下文 - 线程映射类,如下所示

      public class ContextMap : IContextMap
{
private static IContextMap _contextMap;
private Dictionary<int, IArbContext2> ContextDict;
private static string DbName;
private ContextMap()
{
if (string.IsNullOrWhiteSpace(DbName))
throw new InvalidOperationException("Setup must be called before accessing ContextMap");
ContextDict = new Dictionary<int, IArbContext2>();
}

protected internal static void Setup(IContextMap map)
{
_contextMap = map;
}

public static void Setup(string dbName)
{
DbName = dbName;
}

public static IContextMap GetInstance()
{
return _contextMap ?? (_contextMap = new ContextMap());
}


public IArbContext2 GetOrCreateContext()
{
var threadId = Thread.CurrentThread.ManagedThreadId;
if(!ContextDict.ContainsKey(threadId))
ContextDict.Add(threadId,new ArbContext(DbName));
return ContextDict[threadId];
}

public void DestroyContext()
{
if (ContextDict.ContainsKey(Thread.CurrentThread.ManagedThreadId))
ContextDict.Remove(Thread.CurrentThread.ManagedThreadId);
}

代码以某种方式(很少但仍然会发生)在 GetOrCreateContext 方法中抛出 keynotfound 异常。线程是否有可能被转移到一个单独的操作(例如,监督线程强制它执行另一个操作,导致线程在检查 Dict 是否有 key 但返回之前调用 DestroyContext )然后恢复它停止的地方。我从来没有专门这样做过,但我无法理解抛出此错误的任何其他原因。

谢谢。

最佳答案

这里的问题是 Dictionary 不是线程安全的。当多个线程尝试访问它时可能会出现意外行为,即使它们都使用唯一键,因为创建或删除键/值对不是原子操作。

最简单的解决方法是使用 ConcurrentDictionary 代替 ContextDict

关于c# - 托管线程是否可能与自身存在竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23742933/

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