I'm working on a WP7 application that syncs with a cloud-based REST API. To handle the sync there are several calls that have to be sequenced as the result of the last call is used in the next. I'm using RestSharp to handle the call and closures to nest. I'm ending up is a pattern that looks like:
void SyncMe()
{
MyProvider tp = new MyProvider(_userInfo.UserKey);
AccountInfoProvider.GetAccountInfo(_userInfo, (accountInfoArgs) =>
{
if (accountInfoArgs.Status == ResponseStatus.Success) {
var set1 = from t in coll
where t.SyncStatus == SyncStatus.New
select t;
tp.AddRange(set1, (response) =>
{
开发者_运维问答 if (response.Status == ResponseStatus.Success) // Keep going
{
HandleStep1(response.MySet);
var set2 = from t in coll
where t.SyncStatus == SyncStatus.Deleted
select t;
tp.DeleteRange(set2, (deleteResponse) =>
{
if (deleteResponse.Status == ResponseStatus.Success) {
// Check if items were updated on the server since last sync
if (accountInfo.LastEdited > _userInfo.UserLastSync) {
tp.Query(new Query() { ModifiedAfter = _userInfo.UserLastSync }, (results) =>
{
if (results.Status == OperationStatus.Success) {
HandleStep2(tp);
}
else {
}
});
}
else {
HandleStep2(tp);
}
//callback(new SyncCompletedEventArgs(ResponseStatus.Success));
}
else {
}
});
}
else {
}
});
}
else {
}
});
}
}
which admittedly is pretty ugly. Is there a better way to do this? I've tried ManualResetEvents and can't seem to get them to work (when I call WaitOne() the app just hangs). I've been looking up Rx and I'm trying to figure out if it can help in any way here but the documentation isn't screaming a solution out at me. The whole Async model here is complicating the implementation here where sync calls would be simple. Any thoughts on a more elegant approach?
Thanks, K
You might find the Reactive Extensions useful in this scenario. Jesse Liberty has a great series of posts on the Reactive Extensions, the latest of which discusses Asynchronous Callbacks with Rx.
精彩评论