softwaremonster
softwaremonster

Reputation: 663

Locks at C# to use prevent multiple threads or events to use same variable value

I want to free my application from sql, because I do not have a large db. I want to hold my data on memory, so my application will run faster.

My question here is that I've a key pool, and a key can be used by only 4 clients, I want to lock each key when it is registered to a client so I will use:

lock(key)
{
  assignKeyToClient(clientId);
}

If I use that, will lock use the copy of the key or lock the original "key" on ram and does free it after finishing assignment?

Thanks!

Upvotes: 0

Views: 2724

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 161012

I think you are confused on what the lock statement means - it is only for concurrency management - it ensures that the section of code it is protecting (the "critical section") is only entered by one thread at a time.

This has nothing to do with user data, i.e. client id's or keys. To manage unique client id's you could use something like a Dictionary. When you do assign your keys you should use a lock only if there is more than one thread executing this section of code. If that's the case use a private readonly object variable to lock on within your class instance to make sure the same key is only assigned once:

private readonly object myLock = new object();
private Dictionary<int> assignedKeys = new Dictionary<int>();
...

lock(myLock)
{
  int key = PickAKeyHere();
  AssignKeyToClient(key, clientId);
  assignedKeys[key] = clientId; //keep track of which client is assigned what key 
}

Upvotes: 6

Phill
Phill

Reputation: 18804

If you don't have a large database then all your database queries should be < 1 second. You don't have any reason to put all the data in memory. The performance difference by querying the database directly or querying it from memory is negligible.

All you're really doing is over complicating your application. Premature optimization is the root of all evil.

Upvotes: 3

Related Questions