WaitForDownloadAsync Never Returns


#1

This is more of a .NET question than Xamarin. I have a Windows Service that runs periodically to update the data in the ROS from our CRM. On a number of occasions when debugging the service I have noticed that it hangs when running the following code;

var session = driverRealm.GetSession();
Thread.Sleep(250);
AsyncContext.Run(() => session.WaitForDownloadAsync());

I have checked the Nito and Realm documentation and can’t find any information on setting a timeout to circumvent this problem.

Do you have any suggestions?


#2

The AsyncContext.Run(() => session.WaitForDownloadAsync()) will be executed on a different thread which is not supported. Instead, you should wrap all the Realm access logic inside a single AsyncContext.Run block:

AsyncContext.Run(async () =>
{
    using (var realm = await Realm.GetInstanceAsync(...))
    {
        // write some data
        await realm.GetSession().WaitForDownloadAsync();
    }
});

#3

I modified my code as follows;

foreach (DataRow driverRow in drivers)
{
	var userName = driver.Field<string>("UserName");
	var driverId = driverRow.Field<Guid>("DriverId").ToString();
	var driver = GetDbDriver(db, driverId);
	var user = GetRealmUser(db, driver);
	try
	{
		AsyncContext.Run(async () =>
		{
			using (var driverRealm = OpenRealm($"~/{RealmName}", user, userName))
			{
				//await SynchroniseRealm(driverRealm, false, true);
				await driverRealm.GetSession().WaitForDownloadAsync();
				...
			}
		});
	}
	catch (Exception ex)
	{
		Service.LogException(ex.Message));
	}
}

private static async Task SynchroniseRealm(Realm realm, bool upload, bool download)
{
	var session = realm.GetSession();
	//Thread.Sleep(250);
	if (upload) await session.WaitForUploadAsync();
	if (download) await session.WaitForDownloadAsync();
}

And regardless of whether I use SynchroniseRealm (with or without Thread.Sleep) or the syntax shown above, I get an unknown error when executing WaitForDownloadAsync.

The error occurs intermittently, that is; it can occur on the first iteration of the enclosing foreach or any subsequent iteration.

The output window shows;

Exception thrown: 'Realms.Exceptions.RealmException' in mscorlib.dll

And the Exception message contains;

A system error occurred while waiting for completion. See InnerException for more details

And the inner exception contains;

Unknown error


#4

Could this be related to GitHub issue WaitForDownloadAsync often does not terminate after switching from offline to online #1887?


#5

Interesting, can you post the entire exception + stacktrace here? I believe just .ToString-ing it will produce a detailed enough output to investigate. I’m mostly interested in the ErrorCode if there’s one and the stacktrace.