Reputation: 842
I am writing a ASP.NET ApiController that is hosted on IIS. In an action I need to invoke a Web Service named A provided by a company named Tencent. The service requires that I use a key to authenticate. The key is generate by calling another web interface, named B from Tencent and key is valid for 3 hours. Service B has a limitation on calls per day. Therefore I can't call B whenever I want to use A. I can only call B once and store the key in the database for future use.
That means every time I want to use Service A, I need to check the validation of key from database, and if it's expired, call B and get a new one.
Now, when I need to renew my key by calling B, what if before a new key is returned, the ApiController action is called again? The new request would also find that the key in database is stale, then goes on calling B again, invalidating A's newly gained key, causing A to fetch key again, endless loop.
My questions is, how do you get rid of this kind of worry? How do I start? From SQL or IIS or ASP.NET?
I am reading/writing database with EF6 and using ASP.NET MVC 5.
Thanks for your help!
-- Complement -- I was advised to use lock keyword. However I want to have a peace of mind knowing that lock will safe guard the database read/write piece across all IIS requests. So is there any article about how IIS handles multiple requests to the same ASP.NET module and concurrency control on that?
Upvotes: 2
Views: 164
Reputation: 1299
Use a lock around the code in question. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
See https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
If it’s in a clustered environment they you will also need to create a transaction at the database level, which will check the last updated/expiry before performing an update.
Upvotes: 1