Link to home
Create AccountLog in
Avatar of socom1985
socom1985

asked on

c# MSSQL next ID

I have a web service which enters data in an SQL table. Website generates a request for the web service and gets an ID back immediately. Then the web service performs some actions and at last it enters the data with this id in the table. So I have to get the next possible id in the table, retur it to the website, perform some actions then insert the record with this id in the table.

Can you please tell me how I can get sure, that this ID will not be used by another thread? It seams insecure just to get the ID and then insert the record, because the actions which the service performs in between take quite some time. Can I look the table for this time? Will this influence the performance?
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

rather locking the table you can Mutex as synchronization mechanism to ensure that only one thread at a time calls the method which returns next available ID.releasing the Mutex should take place only after the ID was used when inserting the record.then when the next thread asks for next available ID, the previous ID won't be returned cause it was always inserted with the record by the last thread.
from http://msdn.microsoft.com/en-us/library/ms173179%28VS.80%29.aspx:Although a mutex can be used for intra-process thread synchronization, using Monitor is generally preferred, because monitors were designed specifically for the .NET Framework and therefore make better use of resources. In contrast, the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class.
ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer