处理同步方案的多个异步WebRequest

时间:2011-02-23 06:02:49

标签: silverlight windows-phone-7

我正在开发一个与基于云的REST API同步的WP7应用程序。为了处理同步,有几个调用必须按顺序排序,因为最后一个调用的结果是在下一个调用中使用的。我正在使用RestSharp来处理嵌套的调用和闭包。我结束的是一个看起来像这样的模式:

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 {
    }
  });
}

}

这无疑是非常难看的。有一个更好的方法吗?我已经尝试过ManualResetEvents并且似乎无法让它们工作(当我调用WaitOne()应用程序只是挂起)。我一直在寻找Rx而我正在试图弄清楚它是否可以在任何方面提供帮助,但文档并没有尖叫出我的解决方案。这里的整个异步模型使得这里的实现变得复杂,其中同步调用将是简单的。有关更优雅方法的任何想法吗?

谢谢, ķ

1 个答案:

答案 0 :(得分:0)

您可能会发现Reactive Extensions在此方案中很有用。 Jesse Liberty有great series of posts on the Reactive Extensions,其中最新一篇讨论Asynchronous Callbacks with Rx