c# - ConditionalWeakTable.GetOrCreateValue() 中的 IndexOutOfRangeException

标签 c# .net

我正在使用 ConditionalWeakTable作为弱事件处理程序实现的一部分。它工作正常,除了偶尔我从用户那里收到自动崩溃日志,表明对 GetOrCreateValue() 的调用已崩溃。

错误和调用堆栈看起来像以下两个堆栈之一,我假设这取决于是否存在现有条目或需要创建新条目:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.CreateEntry(TKey key, TValue value)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.GetValue(TKey key, CreateValueCallback createValueCallback)
   at [my code]

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.FindEntry(TKey key)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.TryGetValueWorker(TKey key, TValue& value)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.TryGetValue(TKey key, TValue& value)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.GetValue(TKey key, CreateValueCallback createValueCallback)
   at [my code]

(对 GetOrCreateValue() 的实际调用似乎已被内联。)

这是我声明 ConditionalWeakTable 的代码:

private static readonly ConditionalWeakTable<object, Dictionary<EventInfo, object>> s_sourceObjects = new ConditionalWeakTable<object, Dictionary<EventInfo, object>>();

这是我调用 GetOrCreateValue() 的代码:

Dictionary<EventInfo, object> events;
lock(s_sourceObjects)
    events = s_sourceObjects.GetOrCreateValue(sourceObject);

这是引用 s_sourceObjects 字段的唯一其他地方:

bool success;
Dictionary<EventInfo, object> events;
lock(s_sourceObjects)
    success = s_sourceObjects.TryGetValue(sourceObject, out events);

(我添加了 lock 语句,因为我怀疑 ConditionalWeakTable 中存在线程安全错误,尽管文档声称它是线程安全的。但是,错误仍然存​​在即使使用 lock 语句,所以显然这不是线程问题。)

我的应用程序使用 .NET 4.6.2。

我是否以某种方式滥用或不理解 ConditionalWeakTable?或者这是一个框架错误?如果是框架错误,我有什么办法可以解决它吗?

如果有人想查看上下文,这里是该类的完整源代码:https://gist.github.com/waltdestler/2a339bdd0d7d647501eb4690772e3b50

最佳答案

以防万一其他人遇到这个问题,我想跟进问题的根源:

我的程序实际上是一个电子游戏,结果有些玩家使用了一个叫做 Cheat Engine 的工具,可以直接修改内存值。 (例如,更改保存玩家有多少钱的内存。)我发现每当发生此崩溃时 Cheat Engine 都在运行,这让我相信玩家正试图用它在游戏中作弊并且是无意中编辑了错误的内存位置并导致其崩溃。

关于c# - ConditionalWeakTable.GetOrCreateValue() 中的 IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45201247/

相关文章:

c# - 将 Pascal Case 转换为句子的最佳方法

c# - 模式匹配后在 foreach 循环中填充 List<T>

c# - 两个日期之间的天数差异

c# - 使用 Polly 重试之前检查响应的字符串内容

c# - 将 app.config 的 appsettings 部分分成两部分

c# - 关于生成无法追踪的发票 ID 的想法

c# - 在 Visual Studio 中以编程方式应用/停用断点

c# - 为什么我不能使用参数字符串来命名我的按钮?

c# - 将 string[] 转换为 ObservableCollection<string>

c# - 如何通过不同的 .net(c#) 线程处理多个 SQL 事务