不接收来自BeginGetResponse的回调

时间:2012-07-10 15:19:59

标签: c# silverlight

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

我有以下代码:

 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}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

非常感谢所有的帮助!

我最终完成了Simplify Async networking with Tasks in SL5中描述的任务。

HttpWebRequest _request;

private void doGetRequest()
  _request = WebRequestCreator.ClientHttp.Create(new Uri("http://localhost/getDummy")) as HttpWebRequest;
        var webTask = Task.Factory.FromAsync<WebResponse>
            (_request.BeginGetResponse, _request.EndGetResponse, null)
          .ContinueWith(
            task =>
            {
                var response = (HttpWebResponse)task.Result;
                // The reason I use HttpRequest, not WebRequest, to get statuscode.
                if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
                {
                     //Do Stuff
                }
            });

但我认为问题依赖于我的日志记录在回调时没有记录,这是我无法理解的。但是在把头撞到墙上一天之后,我会把它留在后面。但是想想我的实际帖子会有效。