简体   繁体   中英

C# - How to lock a method from being accessed by multiple process

I'm a little struggle with this issue, and will be happy for help -

I have ac# project (.sln) which running on different remote machines - so they create different instances of the same class.. All of them are connect to the same DB, and running the same sql transaction.

I have inside the method that calling DB method to check the data "CanBeHandledByMachine(dalTestRequest, dalMachine, machineCanExecuteUITests)"

which checks if another machine has already got the same data from DB. But, I still have a collisions, 2 machines indeed got the same data, Locking object (mutex) / static class of course will not help in this case...

Wait for your help guys :) Thanks,

You need to handle the locks at the shared resource, ie your database. You don't really state what you're doing but a typical scenario is "claiming" a record to do some processing on.

Your would typically do this by updating the table row (eg a status column -> 'processing', so that it is no longer flagged as needing to be processed) and selecting the relevant columns back to your calling application.

The OUTPUT clause is a good way of doing this, as you acquire an exclusive lock on the row(s) as part of the UPDATE:

https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM