C# 奇怪';索引超出范围';(多线程问题)

C# 奇怪';索引超出范围';(多线程问题),c#,multithreading,indexing,visual-studio-2013,threadstatic,C#,Multithreading,Indexing,Visual Studio 2013,Threadstatic,我正在用C#(Visual Studio 2013)编写一个Windows服务。 该服务为其连接的每台服务器激活一个线程 “服务器”对象定义为“ThreadStatic”(因此每个线程应作为不同的对象访问它): 调试时-有时会出现以下错误: ArgumentOutOfRangeException Index was out of range. Must be non-negative and less than the size of the collection. 它发生在以下行中(“服务器

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

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

调试时-有时会出现以下错误:

ArgumentOutOfRangeException
Index was out of range. Must be non-negative and less than the size of the collection.
它发生在以下行中(“服务器”线程的方法内部):

但奇怪的是,调试器显示值正常:

G.CurServer.FilesList.count = 1
G.CurServer.nFilesIndex = 0
所以应该没有任何错误

当我按F11(调试器步骤)时,它会继续调试,好像一切都很好,分配也正常

为什么0


是Visual Studio中的一个bug在分配当前线程的值之前提示错误吗?或者我没有安全地使用线程(更有可能)?

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

ArgumentOutOfRangeException
Index was out of range. Must be non-negative and less than the size of the collection.
我在线程的方法中使用对象赋值,如下所示:

G.CurServer = server;
而不是像这样克隆对象():

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

我希望它能帮助某人。。。 祝你一切顺利,艾尔

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