【发布时间】:2019-02-16 17:26:57
【问题描述】:
我已根据 Microsoft Sample 在我的 Xamarin Forms 应用程序中提供的文档/示例实现了 Azure - 离线同步。
在提供的示例/文档中,他们使用的是默认服务处理程序。
// 简单的错误/冲突处理。真正的应用程序会通过 IMobileServiceSyncHandler 处理各种错误,如网络状况、服务器冲突等。
因为如果 Pull/Push 失败,我需要实现 3 次重试逻辑。根据文档,我创建了一个自定义服务处理程序( IMobileServiceSyncHandler)。
请在此处找到我的代码逻辑。
public class CustomSyncHandler : IMobileServiceSyncHandler
{
public async Task<JObject> ExecuteTableOperationAsync(IMobileServiceTableOperation operation)
{
MobileServiceInvalidOperationException error = null;
Func<Task<JObject>> tryExecuteAsync = operation.ExecuteAsync;
int retryCount = 3;
for (int i = 0; i < retryCount; i++)
{
try
{
error = null;
var result = await tryExecuteAsync();
return result;
}
catch (MobileServiceConflictException e)
{
error = e;
}
catch (MobileServicePreconditionFailedException e)
{
error = e;
}
catch (MobileServiceInvalidOperationException e)
{
error = e;
}
catch (Exception e)
{
throw e;
}
if (error != null)
{
if(retryCount <=3) continue;
else
{
//Need to implement
//Update failed, reverting to server's copy.
}
}
}
return null;
}
public Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
{
return Task.FromResult(0);
}
}
但我不确定如何处理/恢复服务器副本以防所有 3 次重试失败。
在 TODO 示例中,他们根据 MobileServicePushFailedException。但是当我们实现 IMobileServiceSyncHandler 时,这是可用的。 此外,如果我们包含自定义 IMobileServiceSyncHandler,它不会在 PushAsync / PullAsync 之后执行代码。万一出现异常,即使是 try catch 也不会触发。
try
{
await this.client.SyncContext.PushAsync();
await this.todoTable.PullAsync(
//The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
//Use a different query name for each unique query in your program
"allTodoItems",
this.todoTable.CreateQuery());
}
catch (MobileServicePushFailedException exc)
{
if (exc.PushResult != null)
{
syncErrors = exc.PushResult.Errors;
}
}
// Simple error/conflict handling. A real application would handle the various errors like network conditions,
// server conflicts and others via the IMobileServiceSyncHandler.
if (syncErrors != null)
{
foreach (var error in syncErrors)
{
if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
{
//Update failed, reverting to server's copy.
await error.CancelAndUpdateItemAsync(error.Result);
}
else
{
// Discard local change.
await error.CancelAndDiscardItemAsync();
}
Debug.WriteLine(@"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
}
}
}
注意
在我的应用程序中,我只尝试重试 3 次,以防出现任何服务器错误。我不是在寻找解决冲突的方法。这就是我没有添加相同代码的原因。
如果有人遇到类似问题并解决了,请提供帮助。
斯特兹。
【问题讨论】:
标签: azure xamarin.forms azure-mobile-services