2012-05-21 121 views
1

我有这个代码是为了做一个异步调用,但它不是,请看看它,让我知道哪里出了问题。异步HttpWebRequest不起作用

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); 
} 

哪里出问题了?当我调试它时,它会等待电话继续下去,但这不应该发生。

回答

0

BeginGetResponse被记录为包括同步部分:

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

除此之外,如果你调用FinishWebRequest(从技术上说,如果调用EndGetResponse的请求之前有时间来完成,EndGetResponse将阻止。

这是意料之中的,因为EndGetResponse需要返回到你的对象,你可以从响应数据 - 但它怎么可以返回这样一个对象,如果请求尚未完成?

+0

那么可以做些什么:o – 1Mayur