如何实现递归回调模式?

时间:2012-04-27 13:54:14

标签: c# callback iteration

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

现在我脑子崩溃了,我怎么能把它放在一个迭代循环中,如果不再需要ReDirects,它会在最后一次回调回原来的调用者?

1 个答案:

答案 0 :(得分: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);
}