Domanda

I'm writing a Windows service in C# (Visual Studio 2013). The service activates a thread for each server it connects with.

The 'server' object is defined as 'ThreadStatic' (so each thread should access it as a different object):

[ThreadStatic]
public static Server CurServer

On debug- I sometimes get the error:

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

It occures in the following line (inside the method of the 'server' thread):

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

But the strange thing is that the debugger shows that the values are ok:

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

So there should'nt be any error!!!

When I press F11 (debugger step), it keeps on debugging as if everything is fine and the assignment also works...

Why????? :0

Is it a bug in the Visual Studio that prompts the error before assigning the current thread's values? Or that I'm not using threads saftley (more likely)?

È stato utile?

Soluzione

I can't explain the bad display of VS, but I found the cause of the error:

I used object assignment in the thread's method like this:

G.CurServer = server;

Instead of cloning the object like this (How to Clone Objects):

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

This first assignment caused values of G.CurServer to change in the different threads even though it is [ThreadStatic].

I hope it helps someone... Best wishes, Eyal. http://reginiano.com

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top