Navigation

Write Transactions - .NET SDK

On this page

  • Overview
  • Initiate a Transaction
  • Realm is ACID Compliant

In addition to reading objects, you can create, update , and delete objects from a realm. Because these operations modify the state of the realm, we call them "writes", and all writes to Realm must be within a transaction.

A transaction is a list of read and write operations that Realm treats as a single indivisible operation. In other words, a transaction is all or nothing: either all of the operations in the transaction succeed or none of the operations in the transaction take effect.

All writes must happen in a transaction.

A realm allows only one open transaction at a time. Realm blocks other writes on other threads until the open transaction is complete. Consequently, there is no race condition when reading values from the realm within a transaction.

When you are done with your transaction, Realm either commits it or cancels it:

  • When Realm commits a transaction, Realm writes all changes to disk. For synced realms, Realm queues the change for synchronization with MongoDB Realm.
  • When Realm cancels a write transaction or an operation in the transaction causes an error, all changes are discarded (or "rolled back").

The .NET SDK provides a simple API you can use for most writes. The Write() method wraps all commands into a single transaction and then commits the transaction.

The Write() method is shorthand for using the BeginWrite() and Transaction.Commit() methods. In most cases, using Write() will meet your needs, but if you need finer control over the transaction, use BeginWrite() with one of the Transaction methods (Commit(), Dispose(), or Rollback()). The following code shows how to use both approaches:

// Instantiate a class, as normal.
var dog = new Dog { Id = 42, Name = "Max", Age = 5 };
// Open a thread-safe transaction.
realm.Write(() =>
{
// Add the instance to the realm.
realm.Add(dog);
});
// Open a thread-safe transaction.
var transaction = realm.BeginWrite();
try
{
// Perform a write op...
realm.Add(myDog);
// Do other work that needs to be included in
// this transaction
transaction.Commit();
}
catch (Exception ex)
{
// Something went wrong; roll back the transaction
transaction.Dispose();
}

Realm guarantees that transactions are ACID compliant. This means that all committed write operations are guaranteed to be valid and that clients don't see transient states in the event of a system crash.

Give Feedback

On this page

  • Overview
  • Initiate a Transaction
  • Realm is ACID Compliant