开发者

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

开发者 https://www.devze.com 2023-03-29 04:26 出处:网络
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

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 pr开发者_开发百科actices 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 (e.g. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消