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
/ /
Sync Data

Comprobar el progreso de carga y descarga - .NET SDK

Quizás quieras conocer el estado de las operaciones de sincronización en tu aplicación. Por ejemplo, podrías querer que un código específico se ejecute solo después de que todos los datos se sincronicen con App Services. También podrías querer proporcionar a los usuarios el estado de las operaciones de sincronización.

You can set up your Sync session to wait for changes to be uploaded or downloaded. You can also configure your Sync session to notify when the Sync connection status changes.

Para esperar de forma asincrónica a que se completen los cambios, obtenga la sesión de sincronización desde el Propiedad Realms.Sync.SyncSession y luego llamar a los métodos session.WaitForUploadAsync() o session.WaitForDownloadAsync(). Por ejemplo:

using Realms.Sync;
var realm = Realm.GetInstance(config);
await realm.SyncSession.WaitForDownloadAsync();

..versión cambiada:: 12.0.0

Nota

Flexible Sync progress notifications are not yet fully supported. When using Flexible Sync, downloads only report notifications after changes are integrated. Partition-Based Sync provides ongoing notifications as changes progress downloading. Uploads report ongoing progress notifications for both Sync Modes.

Para supervisar el progreso de sincronizar, obtén la sesión de sincronización desde la propiedad Realms.Sync.SyncSession. Luego, añade una notificación de progreso llamando al método session.GetProgressObservable().

La session.GetProgressObservable El método toma los dos parámetros siguientes:

  • Un parámetro ProgressDirection que puede configurarse en Upload o Download.

  • Un parámetro ProgressMode que se puede establecer en ReportIndefinitely para que las notificaciones continúen hasta que se cancele el registro de la ForCurrentlyOutstandingWork devolución de llamada, o para que las notificaciones continúen hasta que solo se sincronicen los bytes transferibles actualmente.

Cuando te suscribesAdemásde las notificaciones, recibe un objeto SyncProgress que proporciona una estimación del porcentaje de datos restantes a transferir como un valor entre 0 y..10

Ejemplo

En el siguiente ejemplo, nos suscribimos a un observable de progreso en session para escuchar eventos de carga. Cuando se activa esta devolución de llamada, se imprime el progreso de carga como porcentaje.

var session = realm.SyncSession;
var token = session.GetProgressObservable(ProgressDirection.Upload,
ProgressMode.ReportIndefinitely)
.Subscribe(progress =>
{
Console.WriteLine($@"Current upload progress:
{progress.ProgressEstimate * 100}%");
});
token.Dispose();

Once you no longer wish to receive notifications, unregister the token by using token.Dispose().

To get the connection state of a SyncSession, set an event handler on the PropertyChanged event. The event handler is a standard .NET PropertyChangedEventHandler delegate that takes in a sender object and PropertyChangedEventArgs object. In the event handler, cast the sender to a Session object and check if the event argument's PropertyName property is Session.ConnectionState. You can then get the ConnectionState value, which will be one of the following:

  • Conectando

  • Conectado

  • Desconectado

The following code demonstrates setting the event handler, casting the session object, and checking the Sync status:

public void SetupRealm()
{
var appConfig = new AppConfiguration(myRealmAppId);
app = App.Create(appConfig);
user = app.LogInAsync(Credentials.Anonymous()).Result;
config = new PartitionSyncConfiguration("myPartition", user);
try
{
var realm = Realm.GetInstance(config);
var session = realm.SyncSession;
session.PropertyChanged += SyncSessionPropertyChanged!;
realm.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void SyncSessionPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Session.ConnectionState))
{
var session = (Session)sender;
var currentState = session.ConnectionState;
if (currentState == ConnectionState.Connecting)
{
//session is connecting
}
if (currentState == ConnectionState.Connected)
{
//session is connected
}
if (currentState == ConnectionState.Disconnected)
{
//session has been disconnected
}
}
}

Volver

Suspend or Resume a Sync Session

En esta página