简体   繁体   English

共享资源和并发用户 - .NET 中的最佳实践?

[英]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.问题是,没有办法在这些用户之间显式分离资源,所有资源都必须共享:因此,10 个用户可能会打开资源,然后 1 个用户可以修改该资源。

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.更新:更具体地说,当您在 2 个实体之间存在主详细信息依赖关系时,一个用户打开它以删除一些详细信息,而其他用户打开它以添加和修改某些内容,这就是所有情况。 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.这可能只是一个 integer。 Basically when you first query a row, you get the initial value of the Version column.基本上,当您第一次查询一行时,您会得到Version列的初始值。 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.然后在更新行时,将初始版本放在where子句中,然后还更新版本以及其他字段。

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.如果您不想修改所有表以包含Version列,则可以使用下一种技术。 Basically, you put all the original values as part of your where clause:基本上,您将所有原始值作为where子句的一部分:

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.如果您使用的是 NHibernate,则可以根据您设置映射的方式自动为您完成这些技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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