문서 메뉴

문서 홈애플리케이션 개발Atlas Device SDK

쓰기 트랜잭션(write transaction) - .NET SDK

이 페이지의 내용

  • 개요
  • 트랜잭션 시작
  • 트랜잭션 상태 확인

객체를 읽는 것 외에도 영역에서 객체를 생성, 업데이트 및 삭제할 수 있습니다. 이러한 작업은 Realm의 상태를 수정하기 때문에 "쓰기"라고 부르며 Realm에 대한 모든 쓰기는 트랜잭션 내에서 이루어져야 합니다 .

트랜잭션은 Realm이 분할할 수 없는 단일 작업으로 처리하는 읽기 및 쓰기 작업 목록입니다. 트랜잭션은 전부 아니면 아무것도 없는 작업으로, 트랜잭션의 모든 작업이 성공하거나 트랜잭션의 작업이 전혀 적용되지 않습니다.

영역은 한 번에 하나의 열린 트랜잭션만 허용합니다. Realm은 열린 트랜잭션이 완료될 때까지 다른 스레드에서 다른 쓰기를 차단합니다. 이렇게 하면 트랜잭션 내의 영역에서 값을 읽을 때 경쟁 상태가 발생하지 않습니다.

트랜잭션의 모든 작업이 완료되면 Realm은 이를 커밋하거나 트랜잭션을 취소합니다.

  • Realm은 트랜잭션을 커밋하면 모든 변경 사항을 디스크에 씁니다. 동기화된 영역의 경우 SDK는 Atlas App Services와의 동기화를 위해 변경 사항을 대기열에 추가합니다.

  • Realm이 쓰기 트랜잭션(write transaction)을 취소하면(예: 트랜잭션의 작업에서 오류가 발생한 경우) 모든 변경 사항이 삭제됩니다(또는 "롤백").

.NET SDK는 대부분의 쓰기에 사용할 수 있는 간단한 API를 제공합니다. Write()WriteAsync() 와 메서드는 모든 명령을 단일 트랜잭션으로 래핑한 다음 트랜잭션을 커밋합니다.

Write()WriteAsync() 메서드는 BeginWrite()Transaction.Commit() 메서드와 Async 메서드를 사용하기 위한 약식입니다. 대부분의 경우 이 두 가지 쓰기 방법 중 하나가 요구 사항을 충족합니다. 트랜잭션을 더 세밀하게 제어해야 하는 경우 다음 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();
}
}
}

참고

취소 토큰

대부분의 C# 비동기 메서드와 마찬가지로 WriteAsync, BeginWriteAsyncCommitAsync 메서드는 CancellationToken 를 매개 변수로 지정하여 프로세스가 완료되기 전에 작업을 취소할 수 있는 옵션을 제공합니다.

SDK는 현재 트랜잭션 상태가 포함된 TransactionState 속성을 제공합니다. TransactionState 를 사용하여 트랜잭션을 두 번 커밋하거나 롤백하지 않도록 할 수 있습니다.

// 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();
}
}
}
← 스레딩 - .NET SDK