If you need to create a global unique serial number in the program, you must synchronize the process of creating the serial number to prevent the same serial number when multiple concurrent access is prevented. Several methods are listed below for your reference.
Method of utilizing database
The following examples are based on MS SQL Server, and if you can read the Sequence object directly using Oracle, you don't need to perform such complex operations.
Method 1: Using the table lock
Table Structure:
Create Table XTAB (SEQ_ID INT Primary Key, Create_time DateTime)
Store procedure or SQL statement:
Begin TRAN
Declare @MAX_SEQ INT
- Lock table when reading records
SELECT @ max_seq = max (seq_id) from xtab with (Tablockx)
Set @max_seq = isnull (@max_seq, 0)
Set @MAX_SEQ = @ max_seq 1
Print @MAX_SEQ
INSERT INTO XTAB VALUES (@ max_seq, getdate ())
Commit
- The variable @max_seq is stored in the currently generated number
Method 2: Use the self-increment field
If you can lock the table in method 1 by using the self-increment variable, then the record is inserted, and the maximum method is read. However, the following is to insert records through C #, and read the self-integrated field of the recorded record.
Table Structure:
Create Table XTAB_I (SEQ_ID INT IDENTITY (1, 1) Primary Key, Create_Time DateTime)
C # code, using the time handler function to read the value of the @@ iDENTITY variable while the data is updated. Complete Content Reference: OLEDBWrap.cs file.
// Parameter content: // szselectsql = "select * from xtab_i where seq_id isnull"; // sztabname = "xtab_i"; /// /// Create a DataSet object by querying, returning objects for performing insertion Operation /// summary> /// SQL statement param> /// Table name param> /// Insert DataSet object returns>
public DataSet CreateInsertDataSet_bySelect (string szSelectSql, string szTabName) {m_dbAdapter.SelectCommand = new OleDbCommand (szSelectSql, m_dbConn); OleDbCommandBuilder cb = new OleDbCommandBuilder (m_dbAdapter); DataSet ds = new DataSet (); m_dbAdapter.Fill (ds, szTabName); m_dbAdapter .Rowupdated = new oledbroPdateDeventHandler (onrowupdated_inserted); return DS;} // ---------------- Private event handle /// // /// manipulated update event /// summary> /// param> /// param> protected void OnRowUpdated_Inserted (object sender, OleDbRowUpdatedEventArgs args) {OleDbCommand idCMD = new OleDbCommand ( "SELECT @@ IDENTITY", m_dbConn); if (args.StatementType == StatementType.Insert) {object rObj = idCMD.ExecuteScalar (); if (rObj == null) m_iDbIdentity = -1; else if ( Robj.toString ()! = "") m_idbidentity = int32.parse (robj.tostring ()); else m_idbidentity = -1;} idcmd.dispose (); // m_idbidentity variable is included in the current insert column Value of fields}
Utilize program control
Method 1: Using Application objects in ASP.NET
Use the global HTTPApplicationState object in ASP.NET.
C # code:
Application.lock ();
Application ["XLOCK"] = "Locked ';
Try
{// must capture abnormalities and avoid unlocking objects
// Your Code Here
}
Catch (Exception E)
{
}
Application ["XLOCK"] = "UNLOCK";
Method 2: Synchronization using synchronous objects in the operating system
A variety of classes for synchronization are defined under system.threading namespace of the DOTNET framework, such as Mutex, Semaphore. Here is a method of using a mutex MUTEX to implement synchronization.
C # code:
Void test () {// Need to introduce system.threading; // Create a mutex object called MyMutex, if the OS has created the same name object, just re-get your handle
Mutex M = New Mutex (False, "MyMutex"); // Wait for access to access to the access to the access (10 * 1000, false); if (getMutex) {// has obtained access to the right TRY { / / Must capture abnormalities, avoid unlock objects // your code here} m.releasemutex ();} else {// Nothing access}}
In the program, you should try to use Mutex's sync objects to be named to achieve multiple synchronization objects, and synchronize multiple resources. If you want to implement multiple 同 入, you can use the Semaphore.
Other ways: Use the LOCK keyword to prevent the thread from being executed by the same paragraph
C # code:
Class Ctest {Int Balance; Void Increase () {Lock (this) {Balance ;}}}
Since the ASP.NET program may configure different thread modes in IIS, this method can be used in the ASP.NET program without using this method, and this method can be used in conventional applications.
Attachment: OLEDBWrap.cs is a very simple package, encapsulated basic database operations.
Using system; using system.data.oledb;
Namespace WYY.WRAP {/// /// WDBWrap Description: Complete Database Access Function /// 1 Create Connection, Adapter, CONN and Adapter objects in the management object /// 2 Ventate // by SELECT results / 3 Insert /// 4 Update /// summary> public class OLEDBWRAP {// -------- Public Method /// // The database connection is automatically cleared when the object is cleared. Object /// summary> public oledbwrap () {m_dbconn = new oledbconnection (dbstring); m_fautodelconn = true; m_dbadapter = new oledbdataadapter (); m_dbconn.open ();} /// /// By connection String Construction Database Connection Object /// Summary> /// ADO connection string param> public oledbwrap (string strconnection) {m_dbconn = new oledbconnection (strConnection); m_fautodelconn = True; m_dbadapter = new oledbdataadapter (); m_dbconn.open ();} /// /// The database connection object is not automatically cleared when the object is cleared when the object is cleared. /// summary> /// existing database connection object param> public OleDbWrap (OleDbConnection conn) {m_dbConn = conn; m_fAutoDelConn = false; m_dbAdapter = new OleDbDataAdapter (); // m_dbConn.Open ( } public virtual void dispose () {m_dbadapter.dispose (); if (m_fautodelconn) {m_dbconn.close (); m_dbconn.dispose ();}} /// /// Create a DataReader object via SQL statement /// summary> /// SQL statement param> /// DataReader object returns> public oledbdatareader CreateDataReader (String szsql) {OLEDBCommand cmd = new oledbcommand (szsql, m_dbconn); OLEDBDATAREADER DR = cmd.executeReader (); cmd.dispose (); return DR;} /// /// through SQL query statement, return The first line of results can be used to perform a similar statement like SELECT COUNT (*) /// <
/ summary> /// SQL statement param> /// Return to object returns> public object executescalar (string szsql) {oledbcommand idcmd = new oledbcommand (szsql, m_dbconn) Object robj = idcmd.executescalar (); idcmd.dispose (); return robj;} /// /// call oledbcommand ExecuteNonQuery //// summary> /// param> /// returns> public int ExecuteNonQuery (string szSql) {OleDbCommand idCMD = new OleDbCommand (szSql, m_dbConn); int iRet = idCMD.ExecuteNonQuery (); idCMD.Dispose (); return Iret;} /// /// creation query with DataSet object /// summary> /// query SQL statement param> /// table name param> /// DataSet object has been filled returns> public DataSet CreateSelectDataSet (string szSql, string szTabName) {m_dbAdapter.SelectCommand = new OleDbCommand (szSql, m_dbConn); DataSet ds = New DataSet (); m_dbadapter.fill (DS, SZTABNAME); Return DS;} /// /// By querying the voice object, the returned object is used to perform insert operation /// summary> /// SQL statement param> /// Table Name param> /// for inserting returns> public DataSet CreateInsertDataSet_bySelect (string szSelectSql, string szTabName) {m_dbAdapter.SelectCommand = new OleDbCommand (szSelectSql, m_dbConn); OleDbCommandBuilder cb = New OLEDBCommandbuilder (m_dbadapter);
DataSet ds = new DataSet (); m_dbAdapter.Fill (ds, szTabName); m_dbAdapter.RowUpdated = new OleDbRowUpdatedEventHandler (OnRowUpdated_Inserted); return ds;} /// /// DataSet object created by a query, the returned Object is used to perform an update operation /// summary> /// SQL statement param> /// Table name param> //// DataSet object for updating returns> public DataSet CreateUpdateDataSet_bySelect (string szSelectSql, string szTabName) {m_dbAdapter.SelectCommand = new OleDbCommand (szSelectSql, m_dbConn); OleDbCommandBuilder cb = new OleDbCommandBuilder (m_dbAdapter);
DataSet DS = New Dataset (); M_DBADAPTER.FILL (DS, SZTABNAME); Return DS; // m_dbadapter.rowupdated = New OLEDBROWUPDATEDEVENTHANDLER (ONROWUPDATED_UPDATE);} // -------------- - Private event processing /// /// Process data insertion update /// summary> /// param> /// param> protected void onrowupdated_inserted (Object Sender, OLEDBROWUPDATEDEVENTARGS ARGS) {OLEDBCommand IDCMD = New OLEDBCOMMAND (" SELECT @@ Identity ", M_Dbconn);
IF (args.statementtype == statementtype.insert) {Object Robj = idcmd.executescalar (); if (robj == null) m_idbidentity = -1; Else IF (Robj.toDostring ()! = "") m_idbidentity = INT32. Parse (Robj.toString ()); Elsem_idbidentity = -1;} idcmd.dispose ();} // ---------- Public property /// // Insert data After getting the value of the self-increment field in the new data line, you can only support a self-increment field /// summary> public int32 dbidentity {get {return m_idbidentity;}} /// /// database connection character String, saved in the Web.config file section /// summary> public string dbstring {get {return system.configuration.configurationSettings.appsettings ["dbstr"];}} // ------ ------ Public variable /// /// Database connection /// summary> public oledbconnection m_dbconn; /// /// query adapter /// summary> public oledbdataadapter m_dbadapter; public const string m_szrooturl = "/ copathway / TODO /";
// ---------- Private variable /// /// Save database insert is the value of self-increment field /// summary> protected int32 m_idbidentity = -1; protected bool m_fautodelconn = True;}}