Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

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
1

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

app = App.Create(myRealmAppId);
2

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

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

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);
realm.Subscriptions.Add(myItems);
}
};
// 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 demonstrates two ways to create a new Task object and add it to the realm:

var testItem = new Item
{
Name = "Do this thing",
Status = ItemStatus.Open.ToString(),
Assignee = "Aimee"
};
await realm.WriteAsync(() =>
{
realm.Add(testItem);
});
// Or
var testItem2 =
await realm.WriteAsync(() =>
{
return realm.Add<Item>(new Item
{
Name = "Do this thing, too",
Status = ItemStatus.InProgress.ToString(),
Assignee = "Satya"
});
}
);

Important

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.

Back

Sync Data