markus2.0
markus2.0

Reputation: 13

C# - Lock method on value of variable (Threading)

I have not much experience with threading, but in this project I need some Threads to request data from a SPS over the Com-Ports. I have different Threads running and it could happen that 2 or even more Threads would like to access the same Com-Port, which of course doesn't work.
Now my question is if I can lock the called method on the value of a variable which would be the number of the Com-Port, while Threads with a different value can enter the Method.
Btw: I can't use different variables as "keys" for the lock, because I get the values dinamically from a database.
My code could look something like the following:

Main()
{
   Start different Threads calling myMethod
}

myMethod()
{
   lock on value of a Variable
   {
      some code...
   }
}

Upvotes: 0

Views: 1784

Answers (1)

Ofer Barasofsky
Ofer Barasofsky

Reputation: 291

I think your best solution is to create a class that contains myMethod and instantiate it for each port.

If you don't want to do that you can (for example) define a thread safe dictionary of locks

public static ConcurrentDictionary<int, object> locks = new ConcurrentDictionary<int, object>(); 

initialize it before you start your threads:

for (int i=0; i < 10; i++)
{
    locks[i] = new object();
}

and lock by port number:

lock(locks[portnum])
{
    some code...
}

Assuming of course that you know the port number in the context of myMethod (otherwise how would you access the specific port?).

Upvotes: 2

Related Questions