在C# ADO.NET中處理并發(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ā)沖突
}
}
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ā)沖突。