2

所以我有一个带有回调的异步 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);
          }
        }));
      }
    }));
}

现在我的大脑崩溃了,我怎么能把它放在一个迭代循环中,所以如果不再需要重定向,它会最后一次回调给原始调用者?

4

1 回答 1

4

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

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);
}
于 2012-04-27T14:04:22.690 回答