Programmers
asked on
Static method accessed by multiple threads
Hello,
I have a method which performs a search through an array of type Machine. The code is shown below:
===>>>
public static Machine[] egms = new Machine[40];
public static int IndexOf(int pollAdrs, int pollLoop)
{
for(int i = 0; i < egms.Length; i++)
{
if((egms[i].slotPollAddres s == pollAdrs) && (egms[i].slotLoop == pollLoop))
return i;
}
return -1; // Return -1 if not found
}
<<<===
If multiple threads are accessing this method, and since the array 'egms' is static, would this corrupt any of the threads searching parameters? For instance, if a thread calls obj.IndexOf(1,12), it starts searching according to those parameters, 1 and 12. But then if another thread calls say, obj.IndexOf(7,19), will the first thread continue its search according to the (1,12) parameters, or will it be overwritten by the second thread's parameters?
Thanks.
Programmer.
I have a method which performs a search through an array of type Machine. The code is shown below:
===>>>
public static Machine[] egms = new Machine[40];
public static int IndexOf(int pollAdrs, int pollLoop)
{
for(int i = 0; i < egms.Length; i++)
{
if((egms[i].slotPollAddres
return i;
}
return -1; // Return -1 if not found
}
<<<===
If multiple threads are accessing this method, and since the array 'egms' is static, would this corrupt any of the threads searching parameters? For instance, if a thread calls obj.IndexOf(1,12), it starts searching according to those parameters, 1 and 12. But then if another thread calls say, obj.IndexOf(7,19), will the first thread continue its search according to the (1,12) parameters, or will it be overwritten by the second thread's parameters?
Thanks.
Programmer.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sure enumerating thru a collection is not a thread-safe procedure. For this reason you need to lock the collection while enumerating, not lock the object itself but the object returned by the collection SyncRoot method. Like so,
public static Machine[] egms = new Machine[40];
public static int IndexOf(int pollAdrs, int pollLoop)
{
lock ( egms.SyncRoot )
{
for(int i = 0; i < egms.Length; i++) {
if((egms[i].slotPollAddres
return i;
}
return -1; // Return -1 if not found
}
}
:o) I should have refreshed my browser before posting any comment. Nevermind, glad your problem solved.
ASKER
Lol. No problems.
I dont really need to use the SyncRoot method anyway because the method only reads the array and doesn't modify any of its contents. But thanks for the suggestion though.
Kind Regards,
Programmer.
I dont really need to use the SyncRoot method anyway because the method only reads the array and doesn't modify any of its contents. But thanks for the suggestion though.
Kind Regards,
Programmer.
ASKER
Kind Regards,
Programmer.