微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 不接收BeginGetResponse的回调

我无法按照示例来获取回调.

我有以下代码

private void startWebRequest(object sender,EventArgs e)
    {
        Uri url = new Uri("http://localhost.com/dummyGet");
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback),request);
    }

    private void ReadWebRequestCallback(IAsyncResult callbackResult)
    { 
        Console.WriteLine("Don not get here");
        try
        {
            var req = (HttpWebRequest)callbackResult.AsyncState;
            using (var response = req.EndGetResponse(callbackResult))
            {
                Console.WriteLine("Code");
            }
        }
        catch
        {  }
    }

我整天都在反对这个问题,我可以在浏览器中看到get请求,或者在fiddler / wireshark中看到客户端.但是代码(ReadWebRequestCallback)不会被调用.

编辑:
另请注意,如果我使用WebClient和DownloadStringAsync,它可以工作,但我需要其他HTTP状态代码而不是404和200:

_client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);
_client.DownloadStringAsync(_concurrentCheckUrl);
}

private void DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)
    {// Works,gets here}

解决方法

我不确定这是否是解决方案,但在调用回调之前是否已关闭拥有线程?作为银光我怀疑它,但我想我会提出来.

检查http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx – 注意

ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle,new WaitOrTimerCallback(TimeoutCallback),myHttpWebRequest,DefaultTimeout,true);

  // The response came in the allowed time. The work processing will happen in the 
  // callback function.
  allDone.WaitOne();

这可能是你应该尝试Thread.Sleep.如果这不是问题,您是否可以通过添加断点或其他输出语句来确认代码永远不会被激活?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐