简体   繁体   中英

Shared resource and concurrent users - best practices in .NET?

There's an application that is mostly about accessing the database. For the moment, it only allows single user access and I need to make it support multiple concurrent users. The problem is, there's no way to explicitly separate resources between these users, all the resources must be shared: so, 10 users may have the resource open and then 1 can modify that resource.

Are there any frameworks, libraries or at least best practices for solving this problem? It's likely to be quite popular problem, so I believe there should be any of these.

Update : By "resources" I mostly mean the data in database.

Update : To be more specific, it's all about the case when you have a master-details dependency between 2 entities, one user opens it for removing some details and other users opens it to add and modify something. The first one removes the part of data, that the second one was about to modify. And then it happens.

You can use optimistic locking when updating a row. One way to do this is to add a Version column in all your tables. This could just be an integer. Basically when you first query a row, you get the initial value of the Version column. Then when updating the row, you put the initial Version in the where clause and then also update the Version along with the other fields.

UPDATE Product 
SET Version = 2 /* The incremented version */,        
Name = 'UpdatedName',
Description = 'UpdatedDescription'
WHERE  Id = 'SomeUniqueIdXXXX'
AND Version = 1 /* The initial version */

The first update will succeed and the next updates to the same row will fail if they used the stale Version . Your app should be able to handle the failure and proceed the way you want (eg display an error message, etc.). If you don't want to modify all your tables to include a Version column, you can use the next technique. Basically, you put all the original values as part of your where clause:

UPDATE 
Product 
SET Name = 'UpdatedName'
WHERE Id = 'SomeUniqueIdXXXX'
AND Name = 'OriginalName'
AND Description = 'OriginalDescription'

If you are using NHibernate, these techniques can be automatically done for you depending on how you set your mappings.

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