Docs Menu
Docs Home
/ /
Atlas Device SDK
/ /

書込みトランザクション - .NET SDK

項目一覧

  • Overview
  • トランザクションを開始する
  • トランザクションのステータスを確認

オブジェクトの読み取りに加えて、Realm からオブジェクトを作成、更新、および削除することができます。 これらの操作は Realm の状態を変更するため、「書込み (write)」と呼ばれ、Realm へのすべての書込み (write) は トランザクション 内で実行される必要があります

トランザクションは 、Realm が単一の分割不可の操作として取り扱う読み取り操作と書込み (write) 操作のリストです。 トランザクションは、すべての操作または何もない操作です。トランザクション内のすべての操作が成功するか、トランザクション内のどの操作が有効になりません。

Realm では一度に 1 つのトランザクションのみを開くことができます。 Realm は、開いているトランザクションが完了するまで、他のスレッドへの他の書込みをブロックします。 これにより、トランザクション内で Realm から値を読み取るときに競合状態が発生しなくなります。

トランザクション内のすべての操作が完了すると、Realm はそれをコミットするか、トランザクションをキャンセルします。

  • Realm がトランザクションをコミットすると、Realm はすべての変更をディスクに書込みます。 同期された Realm の場合、SDK は Atlas App Services との同期のために変更をキューに入れます。

  • Realm が書込みトランザクションをキャンセルすると(トランザクション内の操作によってエラーが発生した場合など)、すべての変更は破棄されます(または「ロールバック」)。

.NET SDK は、ほとんどの書き込みに使用できるシンプルな API を提供します。 Write()メソッドとWriteAsync()メソッドは、すべてのコマンドを 1 つのトランザクションにラップし、トランザクションをコミットします。

Write()メソッドとWriteAsync()メソッドは、 BeginWrite( ) メソッドとTransaction.Commit()メソッドとそれらのAsyncカウンター部分を使用するための省略形です。 ほとんどの場合、これら 2 つの書込み方法のいずれかでニーズが満たされます。 トランザクションをより詳細に制御する必要がある場合は、次のいずれかのTransactionメソッドとともにBeginWrite()を使用します。

次のコードは、両方のアプローチを使用する方法を示しています。

// 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();
}
}
}

注意

CancelTokens

ほとんどの C# 非同期メソッドと同様に、 WriteAsync BeginWriteAsync CommitAsync メソッドは CancelToken を取得できます は、 プロセスが完了する前に操作をキャンセルするオプションを提供します。

SDK は、現在のトランザクション ステータスを持つTransactionStateプロパティを提供します。 TransactionStateを使用すると、トランザクションを 2 回コミットまたはロールバックしないようにできます。

// 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();
}
}
}

戻る

スレッド化