Docs 菜单
Docs 主页
/ / /
C#/.NET
/

事务

在此页面上

  • 概述
  • 方法
  • 例子
  • 更多信息
  • API 文档

在本指南中,您可以了解如何使用 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()
Starts a transaction on this session and runs the given callback. To learn more about this method, see the withTransaction() page in the Server manual.

重要

处理异常

WithTransaction() 使用的回调函数中捕获异常时,必须在退出 try-catch 块之前重新抛出异常。否则可能会导致无限循环。如果详细了解如何处理这种情况下的异常,请参阅《服务器》手册中的“事务”,并从语言下拉列表中选择 C# 以查看示例。


Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Return Type: 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()
Starts a transaction on this session and runs the given callback. To learn more about this method, see the withTransaction() page in the Server manual.

重要

处理异常

WithTransactionAsync() 使用的回调函数中捕获异常时,必须在退出 try-catch 块之前重新抛出异常。否则可能会导致无限循环。如果详细了解如何处理这种情况下的异常,请参阅《服务器》手册中的“事务”,并从语言下拉列表中选择 C# 以查看示例。


Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Return Type: Task <TResult>

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

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

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

  3. 将文档插入 booksfilms 集合。

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

var books = database.GetCollection<Book>("books");
var films = database.GetCollection<Film>("films");
// Begins transaction
using (var session = mongoClient.StartSession())
{
session.StartTransaction();
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!");
}

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

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

后退

GUID

来年

索引