如何实现递归回调模式



所以我有一个带有回调的异步 Web 请求方法:

private void DoWebRequest(string url, string titleToCheckFor, 
                          Action<MyRequestState> callback)
{
  MyRequestState result = new MyRequestState();
  // ...
  // a lot of logic and stuff, and eventually return either:
  result.DoRedirect = false;
  // or:
  result.DoRedirect = true;
  callback(result);
}

(只是为了提前指出,由于多种原因,我的WebRequest.AllowAutoRedirect设置为false)

我事先不知道我可以期待多少重定向,所以我开始了:

private void MyWrapperCall(string url, string expectedTitle, 
                          Action<MyRequestState> callback)
{
    DoWebRequest(url, expectedTitle, new Action<MyRequestState>((a) =>
    {
      if (a.DoRedirect)
      {
        DoWebRequest(a.Redirect, expectedTitle, new Action<MyRequestState>((b) =>
        {
          if (b.DoRedirect)
          {
            DoWebRequest(b.Redirect, expectedTitle, callback);
          }
        }));
      }
    }));
}

现在我脑部崩溃了,我怎么能把它放在一个迭代循环中,这样如果不再需要重定向,它会对原始调用者进行最后一次回调?

存储对递归方法的引用,以便它可以调用自身:

private void MyWrapperCall(string url, string expectedTitle, Action<MyRequestState> callback)
{
    Action<MyRequestState> redirectCallback = null;
    redirectCallback = new Action<MyRequestState>((state) =>
    {
        if(state.DoRedirect)
        {
            DoWebRequest(state.Redirect, expectedTitle, redirectCallback);
        }
        else
        {
            callback(state);
        }
    });
    DoWebRequest(url, expectedTitle, redirectCallback);
}

最新更新