加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 不接收BeginGetResponse的回调

发布时间:2020-12-15 21:37:07 所属栏目:百科 来源:网络整理
导读:我无法按照示例来获取回调. 我有以下代码: private void startWebRequest(object sender,EventArgs e) { Uri url = new Uri("http://localhost.com/dummyGet"); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.BeginGetRes
我无法按照示例来获取回调.

我有以下代码:

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.如果这不是问题,您是否可以通过添加断点或其他输出语句来确认代码永远不会被激活?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读