在C# ADO.NET中處理并發沖突通常有兩種方式:
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)
{
// 處理并發沖突
}
}
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())
{
// 更新數據
}
reader.Close();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
// 處理異常
}
}
以上是兩種常見的處理并發沖突的方式,開發者可以根據具體情況選擇合適的方式來處理數據更新時可能發生的并發沖突。