Create a unique ordinal in the ASP.net program

Source: Internet
Author: User
Tags datetime implement mutex semaphore table name first row
Asp.net| Program | Create if you need to create a globally unique ordinal in your program, you must synchronize the process that created the ordinal to prevent multiple concurrent accesses with the same number. Here are a few ways for you to refer to.

How to use the database

The following examples are based on MS SQL Server, and if you can read sequence objects directly using Oracle, you do not need to do such a complex operation.

Method 1: Use Table locking

Table structure:

CREATE TABLE Xtab (seq_id int primary key, Create_time datetime)

stored procedure or SQL statement:


BEGIN Tran

DECLARE @max_seq int

--Lock the table when the record is read

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 current generated sequence number

Method 2: Use the self-added field

If you use a self-amplification variable, you can lock the table in method 1 and then insert the record and read the maximum value method. But the following is a ado.net of C # to insert a record and read the self added field of a record that has been inserted.

Table structure:

CREATE TABLE xtab_i (seq_id int IDENTITY (1,1) primary key, Create_time datetime)

C # code that uses the time processing function to read the value of the @ @IDENTITY variable while the data is being updated. Complete content Reference: OleDbWrap.cs file.


Parameter content:
Szselectsql = "SELECT * from xtab_i where seq_id isnull";
Sztabname = "Xtab_i";
<summary>
Creates a DataSet object through a query statement, and the returned object is used to perform the insert operation
</summary>
<param name= "Szselectsql" >sql statement </param>
<param name= "sztabname" > table name </param>
<returns> DataSet object for insertion </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;
}
----------------Private Event handling
<summary>
Handling update events for data insertions
</summary>
<param name= "Sender" ></param>
<param name= "args" ></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 ();
The m_idbidentity variable contains the value of the self-added field of the currently inserted column
}

Using Program control

Method 1: Using the Application object in ASP.net

Leverages the global HttpApplicationState object in asp.net.

C # code:


Application.Lock ();

application["Xlock"]= "locked";

Try

{//The exception must be caught to prevent the object from being unlocked

Your Code here

}

catch (Exception e)

{

}

application["Xlock"]= "unlock";

Method 2: Synchronize with the synchronization objects in the operating system

A variety of classes for synchronization are defined under the System.Threading namespace of the dotnet framework, for example: Mutex,semaphore. The following is a way to implement synchronization using mutex objects.

C # code:


void Test ()
{//need to introduce system.threading;
Create a mutex named Mymutex and simply regain the handle if the OS has already created an object with the same name

Mutex m = new Mutex (false, "Mymutex");
Wait for access in 10 seconds
Boolean getmutex=m.waitone (10*1000,false);
if (Getmutex)
{//access has been obtained
Try
{
An exception must be caught to avoid the inability to unlock the object
Your code here
}
catch (Exception e)
{
}
M.releasemutex ();
}
Else
{
No access rights
}

}

In a program, you should try to use a mutex such as a named synchronization object to achieve the creation of multiple synchronization objects, the purpose of synchronizing multiple resources. If you want to implement multiple joins, you can use semaphore semaphore.

Other method: Use the Lock keyword to prevent a thread from executing concurrently with the same code

C # code:


Class CTest
{
int balance;
void Increase ()
{
Lock (This)
{
balance++;
}
}
}

Because the ASP.net program may configure different threading modes in IIS, you should not use this method to synchronize threads as much as possible in the ASP.net program, which can be used in ordinary applications.

Attached: OleDbWrap.cs, is a very simple encapsulation class, encapsulates the basic database operations.


Using System;
Using System.Data;
Using System.Data.OleDb;

Namespace Wyy.wrap
{
<summary>
Wdbwrap Description: Complete the database access function
1 Create Connection,adapter, manage conn and Adapter objects within the object
2 Populating a DataSet with a select result set
3 Insert
4 Update
</summary>
public class Oledbwrap
{
--------Public methods
<summary>
Automatically clears the database connection object when the object is cleared
</summary>
Public Oledbwrap ()
{
M_dbconn = new OleDbConnection (dbstring);
M_fautodelconn = true;
M_dbadapter = new OleDbDataAdapter ();
M_dbconn.open ();
}
<summary>
Constructing an internal database connection object from a connection string
</summary>
<param name= "strconnection" >ado connection string </param>
Public Oledbwrap (String strconnection)
{
M_dbconn = new OleDbConnection (strconnection);
M_fautodelconn = true;
M_dbadapter = new OleDbDataAdapter ();
M_dbconn.open ();
}
<summary>
Constructs an object from an existing connection and does not automatically purge the database connection object when the object is cleared
</summary>
<param name= "conn" > Existing database Connection objects </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 ();
}
}
<summary>
To create a DataReader object from an SQL statement
</summary>
<param name= "szSQL" >sql statement </param>
<returns>datareader Objects </returns>
Public OleDbDataReader CreateDataReader (string szsql)
{
OleDbCommand cmd = new OleDbCommand (szsql,m_dbconn);
OleDbDataReader dr= cmd. ExecuteReader ();
Cmd. Dispose ();
Return Dr;
}
<summary>
Returns the first row of results from a SQL query statement that can be used to execute a statement similar to select Count (*)
</summary>
<param name= "szSQL" >sql statement </param>
<returns> return Objects </returns>
public Object ExecuteScalar (String szsql)
{
OleDbCommand idcmd = new OleDbCommand (szSQL, m_dbconn);
Object robj = Idcmd.executescalar ();
Idcmd.dispose ();
return robj;
}
<summary>
Call OleDbCommand's ExecuteNonQuery
</summary>
<param name= "szSQL" ></param>
<returns></returns>
public int ExecuteNonQuery (string szsql)
{
OleDbCommand idcmd = new OleDbCommand (szSQL, m_dbconn);
int iRet = Idcmd.executenonquery ();
Idcmd.dispose ();
return iRet;
}
<summary>
Create a query with a DataSet object
</summary>
<param name= "szSQL" > Query SQL statements </param>
<param name= "sztabname" > table name </param>
<returns> DataSet object that has already been populated </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;
}
<summary>
Creates a DataSet object through a query statement, and the returned object is used to perform the insert operation
</summary>
<param name= "Szselectsql" >sql statement </param>
<param name= "sztabname" > table name </param>
<returns> DataSet object for insertion </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;
}
<summary>
Creates a DataSet object from a query statement, and the returned object is used to perform the update operation
</summary>
<param name= "Szselectsql" >sql statement </param>
<param name= "sztabname" > table name </param>
<returns> DataSet object for update </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 handling
<summary>
Handling update events for data insertions
</summary>
<param name= "Sender" ></param>
<param name= "args" ></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 ();
}
------------Public Properties
<summary>
Gets the value of the self-added field in the new data row after inserting the data, only one self-added field is currently supported
</summary>
Public Int32 dbidentity {Get{return m_idbidentity;}}
<summary>
Database connection string, saved in Web.config file <appSettings> section
</summary>
public string Dbstring {get{return system.configuration.configurationsettings.appsettings["dbstr"];}

------------Public variables
<summary>
Database connection
</summary>
Public OleDbConnection M_dbconn;
<summary>
Query Adapter
</summary>
Public OleDbDataAdapter m_dbadapter;
Public Const String M_szrooturl = "/copathway/todo/";

----------Private variables
<summary>
Saving a database insert is the value of a self-added field
</summary>
protected Int32 m_idbidentity =-1;
protected bool M_fautodelconn = TRUE;
}
}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.