Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
CRUD

Write Transactions - .NET SDK

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. A transaction is an all or nothing operation: either all of the operations in the transaction succeed or none of the operations in the transaction take effect.

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

When all operations in a transaction complete, Realm either commits it or cancels the transaction:

  • When Realm commits a transaction, Realm writes all changes to disk. For synced realms, the SDK queues the change for synchronization with Atlas App Services.

  • When Realm cancels a write transaction (as when an operation in the transaction causes an error), all changes are discarded (or "rolled back").

El SDK de .NET proporciona una API sencilla que puede utilizar para la mayoría de las escrituras. Los métodos Write() y WriteAsync() envuelven todos los comandos en una sola transacción y luego confirman la transacción.

La Write() Los métodos y WriteAsync() son una forma abreviada de Async usar BeginWrite() los Transaction métodos BeginWrite() y Transaction.Commit(), y sus equivalentes. En la mayoría de los casos, cualquiera de estos dos métodos de escritura satisfará sus necesidades. Si necesita un control más preciso sobre la transacción, use con uno de estos métodos:

El siguiente código muestra cómo utilizar ambos enfoques:

// 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.
using (var transaction = realm.BeginWrite())
{
// At this point, the TransactionState is "Running":
// transaction.State == TransactionState.Running
try
{
// Perform a write op...
realm.Add(myDog);
// Do other work that needs to be included in
// this transaction
if (transaction.State == TransactionState.Running)
{
transaction.Commit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Something went wrong; roll back the transaction
if (transaction.State != TransactionState.RolledBack &&
transaction.State != TransactionState.Committed)
{
transaction.Rollback();
}
}
}

Nota

CancellationTokens

Al igual que con la mayoría de los métodos asincrónicos de C#, los métodos WriteAsync, BeginWriteAsync y CommitAsync pueden tomar un CancellationToken. como parámetro, proporcionándole la opción de cancelar la operación antes de que se complete el proceso.

El SDK proporciona una propiedad TransactionState con el estado actual de la transacción. Puede usar TransactionState para asegurarse de que no confirmación o rollback una transacción dos veces:

// Open a thread-safe transaction.
using (var transaction = realm.BeginWrite())
{
// At this point, the TransactionState is "Running":
// transaction.State == TransactionState.Running
try
{
// Perform a write op...
realm.Add(myDog);
// Do other work that needs to be included in
// this transaction
if (transaction.State == TransactionState.Running)
{
transaction.Commit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Something went wrong; roll back the transaction
if (transaction.State != TransactionState.RolledBack &&
transaction.State != TransactionState.Committed)
{
transaction.Rollback();
}
}
}

Volver

Enhebrado

En esta página