对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

在C#中使用事务

在本指南中,您可以学习如何使用 MongoDB .NET/C# 驱动程序来执行事务事务允许您运行一系列操作,这些操作在提交事务之前不会更改任何数据。如果事务中的任何操作返回错误,驱动程序就会取消事务,并在所有数据更改变得可见之前将其丢弃。

在 MongoDB 中,事务在逻辑会话中运行。会话是一组要按顺序运行的相关读取或写入操作。会话可以实现一组操作的因果一致性,或支持在 ACID 事务中执行操作。MongoDB 保证事务操作中涉及的数据保持一致,即使操作遇到意外错误。

使用 .NET/C# 驱动程序时,可以从 MongoClient 实例创建一个新会话,并将其类型定义为 IClientSession。我们建议您将客户端重复用于多个会话和事务,而不是每次都实例化新客户端。

警告

仅应将 IClientSession 与创建它的 MongoClient(或关联的 MongoDatabaseMongoCollection)一起使用。将 IClientSession 与其他 MongoClient 一起使用会导致操作错误。

MongoClient 实例上使用同步 StartSession() 或异步 StartSessionAsync() 方法创建 IClientSession。然后,您可以使用 IClientSession 接口提供的方法集来修改会话状态。从以下 Synchronous MethodsAsynchronous Methods 标签页中进行选择,了解管理事务的方法:

方法
说明

StartTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions (optional)

AbortTransaction()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: CancellationToken

CommitTransaction()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

Parameter: CancellationToken

WithTransaction()

在此会话上启动事务并运行给定的回调。要了解有关此方法的更多信息,请参阅服务器手册中的 withTransaction() 页面

IMPORTANT: When catching exceptions within the callback function used by WithTransaction(), you must rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see Transactions in the Server manual and select C# from the language dropdown to view the example.


参数Func <IClientSessionHandle, CancellationToken, Task<TResult>>TransactionOptionsCancellationToken
返回类型Task <TResult>

方法
说明

StartTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions (optional)

AbortTransactionAsync()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: CancellationToken
Return Type: Task

CommitTransactionAsync()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

Parameter: CancellationToken
Return Type: Task

WithTransactionAsync()

在此会话上启动事务并运行给定的回调。要了解有关此方法的更多信息,请参阅服务器手册中的 withTransaction() 页面

IMPORTANT: When catching exceptions within the callback function used by WithTransactionAsync(), you must rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see Transactions in the Server manual and select C# from the language dropdown to view the example.


参数Func <IClientSessionHandle, CancellationToken, Task<TResult>>TransactionOptionsCancellationToken
返回类型Task <TResult>

要配置单个ACID 事务,请将 TransactionOptions实例传递给 StartTransaction()WithTransaction() 方法。本节中的示例将读关注(read concern)设置为 ReadConcern.Majority,写关注(write concern)为 WriteConcern.WMajority

您可以使用以下属性配置 TransactionOptions对象:

属性
说明

MaxCommitTime

Maximum amount of time that a single commitTransaction command can run. If the commit exceeds this limit, MongoDB Server returns a MaxTimeMSExpired error and does not commit the transaction.

If you omit this property, MongoDB Server applies the default transaction runtime limit.

Data Type: TimeSpan?

ReadConcern

Read concern for the transaction. To learn more, see Read Concern in the MongoDB Server manual.

Data Type: ReadConcern

ReadPreference

Read preference for the transaction. To learn more, see Read Preference in the MongoDB Server manual.

Data Type: ReadPreference

WriteConcern

Write concern for the transaction. To learn more, see Write Concern in the MongoDB Server manual.

Data Type: WriteConcern

此示例展示了如何通过以下步骤创建会话、配置ACID 事务选项、创建ACID 事务以及将文档插入到ACID 事务中的多个集合中:

  1. 使用 StartSession() 方法从客户端创建会话。

  2. 创建 TransactionOptions对象以配置ACID 事务。

  3. 使用 StartTransaction() 方法启动事务。

  4. 将文档插入 booksfilms 集合。

  5. 使用 CommitTransaction() 方法提交事务。

var books = database.GetCollection<Book>("books");
var films = database.GetCollection<Film>("films");
// Begins transaction
using (var session = mongoClient.StartSession())
{
// Configures transaction options
var transactionOptions = new TransactionOptions(
readConcern: ReadConcern.Majority,
writeConcern: WriteConcern.WMajority
);
session.StartTransaction(transactionOptions);
try
{
// Creates sample data
var book = new Book
{
Title = "Beloved",
Author = "Toni Morrison",
InStock = true
};
var film = new Film
{
Title = "Star Wars",
Director = "George Lucas",
InStock = true
};
// Inserts sample data
books.InsertOne(session, book);
films.InsertOne(session, film);
// Commits our transaction
session.CommitTransaction();
}
catch (Exception e)
{
Console.WriteLine("Error writing to MongoDB: " + e.Message);
return;
}
// Prints a success message if no error thrown
Console.WriteLine("Successfully committed transaction!");
}

注意

不支持并行操作

.NET/ C#驱动程序不支持在单个ACID 事务中运行并行操作。

要了解有关本指南中提到的概念的更多信息,请参阅服务器手册中的以下页面:

要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: