[C#][ASP.NET]C# or Asp.net 新增時ID 流水序號不重複寫法

  • 179
  • 0
  • C#
  • 2020-05-19

如標題  引言作者 joysdw12使用的方式 做個紀錄...

參考文章如下

https://dotblogs.com.tw/joysdw12/2012/06/07/72668

這篇的重點在於.....用下方這種方式去insert 就不會造成流水號重複

    // 提供Lock鎖定的物件
    private static object thisLock = new object();



    /// 
    /// 鎖定新增按鈕事件
    /// 
    protected void btnLock_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 20; i++)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(LockInsert));
            thread.Start(i);
        }
    }



    /// 
    /// 鎖定新增方法
    /// 
    private void LockInsert(object i)
    {
        
        lock (thisLock)
        {
            using (SqlConnection myConnection = new SqlConnection(SqlDataSource1.ConnectionString))
            {
                SqlCommand myCommand = new SqlCommand();
                myCommand.Connection = myConnection;
                myCommand.CommandText = "Insert Product (ProNo,ProName) values (@ProNo,@ProName)";
                myCommand.Parameters.AddWithValue("@ProNo", GetProductSerialNumber());
                myCommand.Parameters.AddWithValue("@ProName", "Product_" + i);
                myConnection.Open();
                myCommand.ExecuteNonQuery();
            }
        }
    }

 

 

以上文章僅用紀錄資料使用.....