1

I have this code which is meant to make a async call but it is not, please have a look at it and let me know where is it going wrong.

try
{
    byte[] bytes;
    Stream objRequestStream = null;
    bytes = System.Text.Encoding.ASCII.GetBytes(GetJSONforGetMenuDetails(Id, MenuIds));
    wReq = (HttpWebRequest)WebRequest.Create(new Uri("http://" + MobileWLCUrl + urlCreateCacheAPI));
    wReq.ContentLength = bytes.Length;
    wReq.ContentType = "text/x-json";
    wReq.ServicePoint.Expect100Continue = false;
    wReq.Method = "POST";
    objRequestStream = wReq.GetRequestStream();
    objRequestStream.Write(bytes, 0, bytes.Length);
    objRequestStream.Close();
    wReq.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
    //resp = WebAccess.GetWebClient().UploadString("http://" + MobileWLCUrl + urlCreateCacheAPI, GetJSONforGetMenuDetails(Id, MenuIds));
    //EngineException.CreateLog("Cache Created (for Menus: " + MenuIds + ") in API for LocationId: " + Id);
}
catch (Exception ex) { EngineException.HandleException(ex); }

void FinishWebRequest(IAsyncResult result)
{
    WebResponse wResp = wReq.EndGetResponse(result) as WebResponse;
    StreamReader sr = new StreamReader(wResp.GetResponseStream());
    String res = sr.ReadToEnd();
    EngineException.CreateLog("Cache Created (for Menus: " + MenuIds + ") in API for LocationId: " + LocId);
}

Where is it going wrong? When I debug it, it waits for the call to get over to continue, but that should not happen.

4

1 回答 1

0

BeginGetResponse记录为包括同步部分:

BeginGetResponse 方法需要在此方法变为异步之前完成一些同步设置任务(例如 DNS 解析、代理检测和 TCP 套接字连接)。因此,永远不应在用户界面 (UI) 线程上调用此方法,因为它可能需要一些时间,通常是几秒钟。在某些未正确配置 webproxy 脚本的环境中,这可能需要 60 秒或更长时间。

除此之外,如果您在请求有时间完成之前FinishWebRequest调用(从技术上讲,如果您调用EndGetResponse) ,将会阻塞。EndGetResponse

EndGetResponse这是意料之中的,因为需要向您返回一个可以从中获取响应数据的对象——但是如果请求尚未完成,它如何返回这样的对象呢?

于 2012-05-21T10:46:17.003 回答