简体   繁体   English

如何使用WCF PerCall服务保护资源

[英]How to protect resource using WCF PerCall Service

I'm using a WCF service which needs to be a per call service to handle load, but there are certain methods in the service which need to be thread safe. 我正在使用WCF服务,该服务需要是每个调用服务来处理负载,但是该服务中的某些方法需要是线程安全的。

eg 例如

void CreateCustomer(Customer customer)
{
//If customer does not exists in DB
   //Create customer
}

I'm worried that if there are two calls to create customer (with the same details), I risk have two customer creating in the database, when I really only expected one. 我担心如果有两次调用来创建客户(具有相同的详细信息),则冒着在数据库中创建两个客户的风险,而我真的只希望一个。

Is there some way to solve this problem while allowing my service to remain per call? 有什么办法可以解决此问题,同时让我的服务保持在每次通话中?

You are confusing thread safety with database concurrency. 您将线程安全与数据库并发混淆了。 PerCall service does not pose thread-safety issues, unless you are spawning multiple threads in your service routine (which you should avoid). PerCall服务不会带来线程安全问题,除非您在服务例程中产生了多个线程(应避免)。

Your question should be rephrased that you are concerned with database consistency and concurrency on the Customer table during an insert (eg not seeing a customer that somebody else has created). 应该改写您的问题,使您担心插入过程中“客户”表上的数据库一致性和并发性(例如,看不到别人创建的客户)。

There is a very standardized way in a relational database that fulfills the ACID properties (atomicity, consistency, isolation, durability) to deal with this: Wrap the check/insert in a transaction. 关系数据库中有一种非常标准化的方法,可以满足ACID属性(原子性,一致性,隔离性,持久性)来处理此问题: 将检查/插入事务中。

It will be better for you to write a stored procedure (say CreateCustomerIfNotExists ) that has a transaction and checks if a certain customer ID exists, and will insert a new row into the table if it doesn't exist. 最好编写一个具有事务的存储过程(例如CreateCustomerIfNotExists ),并检查是否存在某个客户ID,如果不存在则将新行插入表中。

The relational database's ACID properties automatically prevents what you fear from happening. 关系数据库的ACID属性会自动防止发生您担心的事情。

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

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