Docs Menu

Docs HomeRealm

Add Device Sync to an App - .NET SDK

On this page

  • Connect to the App Services backend
  • Authenticate a user
  • Open a Synced Realm
  • Use the Realm

Pass the App ID for your App, which you can find in the App Services UI.

app = App.Create(myRealmAppId);

Authenticate a user in your client project. Here, we'll use anonymous authentication.

var user = await app.LogInAsync(Credentials.Anonymous());

To open the realm as a synced realm, you can specify whether a synced realm should download data before it opens. Here, we use a Flexible Sync configuration and specify that the SDK should always download the most recent updates before opening the realm. We also bootstrap the realm with an initial subscription.

var config = new FlexibleSyncConfiguration(app.CurrentUser)
PopulateInitialSubscriptions = (realm) =>
var myItems = realm.All<Item>().Where(n => n.OwnerId == myUserId);
// The process will complete when all the user's items have been downloaded.
var realm = await Realm.GetInstanceAsync(config);

The syntax to read, write, and watch for changes on a synced realm is identical to the syntax for non-synced realms. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.

The following code creates a new Task object and writes it to the realm:

var testItem = new Item
Name = "Do this thing",
Status = ItemStatus.Open.ToString(),
Partition = "myPart"
await realm.WriteAsync(() =>


When Using Sync, Avoid Synchronous Writes on the Main Thread

Because Realm performs sync integrations on a background thread, if you do a synchronous write to your realm on the main thread, there's a small chance your UI could appear to hang as it waits for the background sync thread to finish a write transaction. Therefore, it's a best practice not to do a synchronous write on the main thread when using Device Sync and instead use asynchronous writes with realm.WriteAsync.

←  Sync Data Between Devices - .NET SDKConfigure & Open a Synced Realm - .NET SDK →
Share Feedback
© 2023 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.