使用事件处理程序使应用程序在发布请求后等待网站 returns 响应

Make application to wait after posting request till Website returns response using Event Handlers

我想编写一个事件处理程序,当网站 return 有一些响应时触发一个方法。

我的应用程序通过从几个网站发布 URL 来获取响应。不幸的是,网站 return 有时会在延迟(可能需要 1 到 5 秒)后响应,这会导致我的应用程序抛出错误,因为下一个请求会在不等待上一个请求获得响应的情况下执行。

我实际上可以在应用程序发布的每个请求之后设置休眠时间,但这似乎不是正确的方法,因为如果我将休眠时间设置为 5 秒并且假设网站 return 的响应在 1使进程不必要地多等待 4 秒的秒数。

为了节省一些处理时间,我决定添加事件处理程序,它应该允许应用程序在我们收到上一个请求的响应后 运行 下一个请求。

所以我尝试了类似的方法,我可以调用触发器,但它没有按我想要的方式工作。

我的目的是创建触发器,在收到对上一个请求的响应后向 运行 发出下一个请求,最多可以等待 5 秒。

谁能帮我解决这个问题,在此先感谢。

public delegate void ChangedEventHandler(string response);

public class ListWithChangedEvent : EventArgs
{
    public event ChangedEventHandler Changed;

    protected virtual void OnChanged(string response) 
    {
        if (Changed != null)
         {
             Changed(response);
         }
      }

  public void Validate(string response) 
  {
      OnChanged(response);
  }
}

public class EventListener 
{
  private ListWithChangedEvent _list;

  public EventListener(ListWithChangedEvent list) 
  {
      _list = list;
      _list.Changed += new ChangedEventHandler(ListChanged);
  }

  private void ListChanged(string response) 
  {
      if (!response.IsEmpty())
      {
          return;
      }
  }
}

//请求发布后验证响应

private void _postRequestAndParseResponse()
    {
       _performPostRequest(_returnTailPart(_urls.CommonUrl), argumentsList);

        ListWithChangedEvent list = new ListWithChangedEvent();

        EventListener listener = new EventListener(list);

        list.Validate(_docNode.InnerHtml);
   }

HTTP 超时是大多数 HTTP 客户端的内置功能,是指定超时请求 Web 资源的最简单方法。

如果您使用的是 WebRequest,则可以使用它的超时 属性。这是一个例子:

public void Test()
{
    const int timeoutMs = 5000;
    sw.Start();
    RequestWithTimeout("https://google.com", timeoutMs);
    RequestWithTimeout("http://deelay.me/7000/google.com", timeoutMs);
    RequestWithTimeout("http://thisurelydoesnnotexist.com", timeoutMs);
    RequestWithTimeout("http://google.com", timeoutMs);
}

private void RequestWithTimeout(string url, int timeoutMs)
{
    try
    {
        Log("Webrequest at " + url + " starting");
        WebRequest req = WebRequest.Create(url);
        req.Timeout = timeoutMs;                                
        var response = req.GetResponse();                
        Log("Webrequest at " + url + " finished");
    }
    catch (WebException webException)
    {
        Log("WebRequest failed: " + webException.Status);
    }
    catch (Exception ex)
    {
        Log(ex.ToString());
    }

}

输出:

    0ms | Webrequest at https://google.com starting
  169ms | Webrequest at https://google.com finished
  170ms | Webrequest at http://deelay.me/7000/google.com starting
 5186ms | WebRequest failed: Timeout
 5186ms | Webrequest at http://thisurelydoesnnotexist.com starting
 5247ms | WebRequest failed: NameResolutionFailure
 5247ms | Webrequest at http://google.com starting
 5311ms | Webrequest at http://google.com finished

如果您使用的是 WebClient,您还可以轻松配置超时。检查这个答案:

如果您确实需要在方法调用级别实现超时,请查看: Implementing a timeout on a function returning a value

如果 none 这些答案对您有用,请告诉我们您是如何请求网络资源的。

您尚未指定调用网址的方式。如果您使用 HttpClint (http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client),则可以按如下方式完成:

using(var client = new HttpClient())
{
    var task = client.PostAsync(url1, ..., ...);

    if(!task.wait(5000))
    {
        //task not completed in specified interval (5 sec), take action accordingly.
    }
    else
    {
        // task completed within 5 second, take action accordingly, you can access the response using task.Result
    }

    // Continue with other urls as needed
}

也可以有很多其他方式。如果这不能回答您的问题,请 post 调用 url 的代码。