C# ADO.NET中如何處理并發(fā)沖突

c#
小樊
93
2024-06-25 09:14:37

在C# ADO.NET中處理并發(fā)沖突通常有兩種方式:

  1. 使用樂(lè)觀并發(fā)控制:在進(jìn)行數(shù)據(jù)更新之前,先查詢數(shù)據(jù)的當(dāng)前版本號(hào)或時(shí)間戳,并在更新數(shù)據(jù)時(shí)檢查這個(gè)版本號(hào)或時(shí)間戳是否和數(shù)據(jù)庫(kù)中的一致。如果一致,則更新數(shù)據(jù),如果不一致,則認(rèn)為發(fā)生了并發(fā)沖突。在ADO.NET中可以使用CommandBuilder對(duì)象生成Update語(yǔ)句時(shí)指定參數(shù)檢查并發(fā)沖突。
string updateCommand = "UPDATE Table SET Column = @value WHERE ID = @id AND Version = @version";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    SqlCommand command = new SqlCommand(updateCommand, connection);
    command.Parameters.AddWithValue("@value", updatedValue);
    command.Parameters.AddWithValue("@id", id);
    command.Parameters.AddWithValue("@version", currentVersion);

    int rowsAffected = command.ExecuteNonQuery();

    if (rowsAffected == 0)
    {
        // 處理并發(fā)沖突
    }
}
  1. 使用悲觀并發(fā)控制:在進(jìn)行數(shù)據(jù)更新之前,先鎖定數(shù)據(jù),確保只有一個(gè)線程可以修改數(shù)據(jù)。在ADO.NET中可以使用事務(wù)來(lái)實(shí)現(xiàn)悲觀并發(fā)控制。
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    
    SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.Serializable);

    try
    {
        SqlCommand command = connection.CreateCommand();
        command.Transaction = transaction;

        command.CommandText = "SELECT * FROM Table WITH (UPDLOCK) WHERE ID = @id";
        command.Parameters.AddWithValue("@id", id);

        SqlDataReader reader = command.ExecuteReader();

        if (reader.Read())
        {
            // 更新數(shù)據(jù)
        }

        reader.Close();

        transaction.Commit();
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        // 處理異常
    }
}

以上是兩種常見(jiàn)的處理并發(fā)沖突的方式,開(kāi)發(fā)者可以根據(jù)具體情況選擇合適的方式來(lái)處理數(shù)據(jù)更新時(shí)可能發(fā)生的并發(fā)沖突。

0