【问题标题】:Strange 'Index was out of range' (Multithreading issue)奇怪的“索引超出范围”(多线程问题)
【发布时间】:2014-04-27 12:37:30
【问题描述】:

我正在用 C# (Visual Studio 2013) 编写 Windows 服务。 该服务为其连接的每个服务器激活一个线程。

“服务器”对象被定义为“ThreadStatic”(因此每个线程都应该将其作为不同的对象访问):

[ThreadStatic]
public static Server CurServer

在调试时 - 我有时会收到错误:

ArgumentOutOfRangeException
Index was out of range. Must be non-negative and less than the size of the collection.

它出现在以下行(在“服务器”线程的方法内):

EventConn.FindString = G.CurServer.FilesList[G.CurServer.nFilesIndex].SearchString;

但奇怪的是调试器显示的值是ok的:

G.CurServer.FilesList.count = 1
G.CurServer.nFilesIndex = 0

所以不应该有任何错误!!!

当我按 F11(调试器步骤)时,它会继续调试,好像一切都很好,并且分配也有效......

为什么???? :0

在分配当前线程的值之前提示错误的Visual Studio中是否存在错误?或者我没有使用线程 saftley(更有可能)?

【问题讨论】:

    标签: c# multithreading indexing visual-studio-2013 threadstatic


    【解决方案1】:

    我无法解释VS显示不好,但我找到了错误原因:

    我在线程的方法中使用对象赋值是这样的:

    G.CurServer = server;
    

    而不是像这样克隆对象 (How to Clone Objects):

    G.CurServer = (Server).Clone();
    

    第一次赋值导致 G.CurServer 的值在不同线程中发生变化,即使它是 [ThreadStatic]。

    我希望它可以帮助某人... 最良好的祝愿,埃亚尔。 http://reginiano.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多