Link to home
Start Free TrialLog in
Avatar of Programmers
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].slotPollAddress == 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.

ASKER CERTIFIED SOLUTION
Avatar of ajitanand
ajitanand

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Programmers
Programmers

ASKER

Thanks for that Ajit. It was very useful.

Kind Regards,

Programmer.

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].slotPollAddress == pollAdrs) && (egms[i].slotLoop == pollLoop))
                   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.
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.