我正在使用Azure Mobile App和Xamarin.Forms来创建一个支持离线的移动应用程序。
我的解决方案基于https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter3/client/
以下是我用于离线同步的代码:
public class AzureDataSource
{
private async Task InitializeAsync()
{
// Short circuit - local database is already initialized
if (client.SyncContext.IsInitialized)
{
return;
}
// Define the database schema
store.DefineTable<ArrayElement>();
store.DefineTable<InputAnswer>();
//Same thing with 16 others table
...
// Actually create the store and update the schema
await client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
}
public async Task SyncOfflineCacheAsync()
{
await InitializeAsync();
//Check if authenticated
if (client.CurrentUser != null)
{
// Push the Operations Queue to the mobile backend
await client.SyncContext.PushAsync();
// Pull each sync table
var arrayTable = await GetTableAsync<ArrayElement>();
await arrayTable.PullAsync();
var inputAnswerInstanceTable = await GetTableAsync<InputAnswer>();
await inputAnswerInstanceTable.PullAsync();
//Same thing with 16 others table
...
}
}
public async Task<IGenericTable<T>> GetTableAsync<T>() where T : TableData
{
await InitializeAsync();
return new AzureCloudTable<T>(client);
}
}
public class AzureCloudTable<T>
{
public AzureCloudTable(MobileServiceClient client)
{
this.client = client;
this.table = client.GetSyncTable<T>();
}
public async Task PullAsync()
{
//Query name used for incremental pull
string queryName = $"incsync_{typeof(T).Name}";
await table.PullAsync(queryName, table.CreateQuery());
}
}
问题是,即使没有任何东西可以拉动(Android设备上8-9秒,拉动整个数据库超过25秒),同步也会耗费大量时间。
我查看了Fiddler,了解Mobile Apps BackEnd需要多长时间才能响应,每个请求大约需要50毫秒,所以问题似乎不是来自这里。
有人有同样的麻烦吗?有什么东西我做错了或提示我提高同步性能?
我们的特定问题与我们的数据库迁移有关。数据库中的每一行都具有相同的updatedAt
值。我们运行了一个SQL脚本来修改它们,以便它们都是唯一的。
这个修复实际上是我们遇到的其他一些问题,并不是因为某些未知原因而返回所有行,但我们也看到了显着的速度改进。
此外,另一个改善加载时间的奇怪修复如下。
在我们第一次提取所有数据之后(可以理解地需要一些时间) - 我们在返回的一行上做了一个UpdateAsync()
,之后我们没有推它。
我们已经明白,离线同步的工作方式是,它会提取任何日期比最新更新日期更新的日期。与此相关的速度有了很小的提升。
最后,我们为提高速度而做的最后一件事是,如果已经在视图中缓存了一个副本,则不会再次获取数据。这可能不适用于您的用例。
public List<Foo> fooList = new List<Foo>
public void DisplayAllFoo()
{
if(fooList.Count == 0)
fooList = await SyncClass.GetAllFoo();
foreach(var foo in fooList)
{
Console.WriteLine(foo.bar);
}
}
编辑2019年3月20日:随着这些改进的到位,我们仍然看到非常慢的同步操作,以与OP中提到的相同的方式使用,也包括我的答案中列出的改进。
我鼓励大家分享他们关于如何提高速度的解决方案或想法。