开发者

How to protect resource using WCF PerCall Service

开发者 https://www.devze.com 2023-02-17 02:32 出处:网络
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.

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.

e.g.

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开发者_StackOverflow中文版 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).

Your question should be rephrased that you are concerned with database consistency and concurrency on the Customer table during an insert (e.g. 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.

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.

The relational database's ACID properties automatically prevents what you fear from happening.

0

精彩评论

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

关注公众号