Skip to content

Commit 0dea3a7

Browse files
committed
CSHARP-2315: Write reference docs for sessions and transactions.
1 parent fb32f93 commit 0dea3a7

File tree

1 file changed

+228
-0
lines changed

1 file changed

+228
-0
lines changed
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
+++
2+
date = "2018-06-29T13:45:00Z"
3+
draft = false
4+
title = "Sessions and Transactions"
5+
[menu.main]
6+
parent = "Reference Reading and Writing"
7+
weight = 30
8+
pre = "<i class='fa'></i>"
9+
+++
10+
11+
## Sessions
12+
13+
A session is used to group together a series of operations that are related to each other and should be executed with the same session options. Sessions are also used for transactions.
14+
15+
New overloaded methods that take a session parameter have been added for all operation methods in the driver. You execute multiple operations in the same session by passing the same session value to each operation.
16+
17+
When you call an older operation method that does not take a session parameter, the driver will start an implicit session to execute that one operation and then immediately end the implicit session.
18+
19+
### StartSession and StartSessionAsync
20+
21+
```csharp
22+
IClientSessionHandle StartSession(ClientSessionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
23+
Task<IClientSessionHandle> StartSessionAsync(ClientSessionOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
24+
```
25+
26+
A session is started by calling the StartSession or StartSessionAsync methods of IMongoClient:
27+
28+
You must end a session when you no longer need it. You end a session by calling Dispose, which will happen automatically if you put the session inside a using statement.
29+
30+
The recommended way of using a session is:
31+
32+
```csharp
33+
var sessionOptions = new ClientSessionOptions { ... };
34+
using (var session = client.StartSession(sessionOptions, cancellationToken))
35+
{
36+
// execute some operations passing the session as an argument to each operation
37+
}
38+
```
39+
40+
or
41+
42+
```csharp
43+
var sessionOptions = new ClientSessionOptions { ... };
44+
using (var session = await client.StartSessionAsync(sessionOptions, cancellationToken))
45+
{
46+
// execute some operations passing the session as an argument to each operation
47+
}
48+
```
49+
50+
A session is typically short lived. You start a session, execute some operations, and end the session.
51+
52+
### ClientSessionOptions
53+
54+
The ClientSessionOptions class is used to specify any desired options when calling StartSession.
55+
56+
```csharp
57+
public class ClientSessionOptions
58+
{
59+
public bool? CausalConsistency { get; set; }
60+
public TransactionOptions DefaultTransactionOptions { get; set; }
61+
}
62+
```
63+
64+
#### CausalConsistency
65+
66+
Set to true if you want all operations in a session to be causally consistent.
67+
68+
#### DefaultTransactionOptions
69+
70+
You can provide default transaction options to be used for any options that are not provided when StartTransaction is called.
71+
72+
### IClientSession properties and methods
73+
74+
The IClientSession interface defines the properties and methods available on a session.
75+
76+
```csharp
77+
public interface IClientSession : IDisposable
78+
{
79+
IMongoClient Client { get; }
80+
BsonDocument ClusterTime { get; }
81+
bool IsInTransaction { get; }
82+
BsonTimestamp OperationTime { get; }
83+
ClientSessionOptions Options { get; }
84+
85+
void AdvanceClusterTime(BsonDocument newClusterTime);
86+
void AdvanceOperationTime(BsonTimestamp newOperationTime);
87+
88+
// see also transaction related methods documented below
89+
}
90+
```
91+
Note: a few members of IClientSession have been deliberately omitted from this documentation, either because they are rarely used or because they are for internal use only.
92+
93+
#### Client
94+
95+
The Client property returns a reference to the IMongoClient instance that was used to start this session.
96+
97+
#### ClusterTime
98+
99+
The ClusterTime property returns the highest cluster time that has been seen by this client. The value is an opaque BsonDocument containing a cluster time that has been returned by the server. While an application might never inspect the actual value, it might set this value (by calling AdvanceClusterTime) when initializing a causally consistent session.
100+
101+
### IsInTransaction
102+
103+
Specifies whether the session is currently in a transaction. A session is in a transaction after StartTransaction has been called and until either AbortTransaction or CommitTransaction has been called.
104+
105+
### OperationTime
106+
107+
The operation time returned by the server for the most recent operation in this session. Operation times are used by the driver to ensure causal consistency when the ClientSessionOptions specify that causal consistency is desired. While an application might never use the actual value, it might set this value (by calling AdvanceOperationTime) when initializing a causally consistent session.
108+
109+
### Options
110+
111+
Returns the options that were passed to StartSession.
112+
113+
### AdvanceClusterTime and AdvanceOperationTime
114+
115+
```csharp
116+
void AdvanceClusterTime(BsonDocument newClusterTime);
117+
void AdvanceOperationTime(BsonTimestamp newOperationTime);
118+
```
119+
120+
Call these methods to advance the cluster and operation times when you want subsequent operations in this session to be causally consistent with operations that have executed outside of this session. Typically the values you pass to AdvanceClusterTime and AdvanceOperation time will come from the ClusterTime and OperationTime properties of some other session.
121+
122+
### Transaction methods
123+
124+
The methods to start, abort or commit a transaction are documented in the next section.
125+
126+
## Transactions
127+
128+
Transactions are started, committed or aborted using methods of IClientSession. A session can only execute one transaction at a time, but a session can execute more than one transaction as long as each transaction is committed or aborted before the next one is started.
129+
130+
### StartTransaction
131+
132+
```csharp
133+
void StartTransaction(TransactionOptions transactionOptions = null);
134+
```
135+
136+
Start a transaction by calling StartTransaction, optionally specifying options for the transaction.
137+
138+
Each transaction option can be specified at any of the following levels:
139+
140+
1. StartTransaction in the options parameter
141+
2. StartSession in the defaultTransactionOptions parameter
142+
3. Defaulted
143+
144+
You can specify different options at different levels. An option specified in StartTransaction overrides the same option specified in the defaultTransactionOptions passed to StartSession, which in turn overrides the default value.
145+
146+
#### TransactionOptions
147+
148+
```csharp
149+
public class TransactionOptions
150+
{
151+
public ReadConcern ReadConcern { get; };
152+
public ReadPreference ReadPreference { get; };
153+
public WriteConcern WriteConcern { get; };
154+
155+
public TransactionOptions(
156+
Optional<ReadConcern> readConcern = default(Optional<ReadConcern>),
157+
Optional<ReadPreference> readPreference = default(Optional<ReadPreference>),
158+
Optional<WriteConcern> writeConcern = default(Optional<WriteConcern>));
159+
160+
public TransactionOptions With(
161+
Optional<ReadConcern> readConcern = default(Optional<ReadConcern>),
162+
Optional<ReadPreference> readPreference = default(Optional<ReadPreference>),
163+
Optional<WriteConcern> writeConcern = default(Optional<WriteConcern>))
164+
}
165+
```
166+
167+
Create an instance of TransactionOptions either by calling the constructor with any desired optional arguments, or by calling the With method on an existing instance of TransactionOptions to create a new instance with some values changed.
168+
169+
##### ReadConcern
170+
171+
The ReadConcern used while in the transaction. All operations in the transaction use the ReadConcern specified when StartTransaction is called.
172+
173+
##### ReadPreference
174+
175+
The ReadPreference used while in the transaction. Currently, the ReadPreference for a transaction must be Primary.
176+
177+
##### WriteConcern
178+
179+
The WriteConcern used for this transaction. The WriteConcern only applies when committing the transaction, not to the individual operations executed while in the transaction.
180+
181+
### CommitTransaction and CommitTransactionAsync
182+
183+
```csharp
184+
void CommitTransaction(CancellationToken cancellationToken = default(CancellationToken));
185+
Task CommitTransactionAsync(CancellationToken cancellationToken = default(CancellationToken));
186+
```
187+
188+
You must call CommitTransaction or CommitTransactionAsync in order for a transaction to be committed. If a session is ended while a transaction is in progress the transaction will be automatically aborted.
189+
190+
The commit is executed with the WriteConcern specified by the transaction options.
191+
192+
### AbortTransaction and AbortTransactionAsync
193+
194+
```csharp
195+
void AbortTransaction(CancellationToken cancellationToken = default(CancellationToken));
196+
Task AbortTransactionAsync(CancellationToken cancellationToken = default(CancellationToken));
197+
```
198+
199+
Call AbortTransaction or AbortTransactionAsync to abort a transaction. Since any transaction in progress is automatically aborted when a session is ended, you can also implicitly abort an uncommitted transaction by simply ending the session.
200+
201+
In this example we rely on the implied transaction abort:
202+
203+
```csharp
204+
using (var session = client.StartSession())
205+
{
206+
session.StartTransaction();
207+
// execute operations using the session
208+
session.CommitTransaction(); // if an exception is thrown before reaching here the transaction will be implicitly aborted
209+
}
210+
```
211+
212+
When writing an async program you may want to avoid using the implied abort transaction that occurs when Dispose is called on a session with a transaction in progress, because Dispose is a blocking operation. To be fully async, even in the case where the transaction needs to be aborted, you might instead write:
213+
214+
```csharp
215+
using (var session = await client.StartSessionAsync())
216+
{
217+
try
218+
{
219+
// execute async operations using the session
220+
}
221+
catch
222+
{
223+
await session.AbortTransactionAsync(); // now Dispose on the session has nothing to do and won't block
224+
throw;
225+
}
226+
await session.CommitTransactionAsync();
227+
}
228+
```

0 commit comments

Comments
 (0)