如何同步等待HttpWebRequest回调方法获取响应

时间:2015-01-23 09:27:06

标签: c# wcf windows-phone-8 synchronization httpwebrequest

public void RemoteInsert()  
{
        String dataSet = "dataset=" + json.ToString();  
        accessKey = mobRemoteDB.accessKey;  
        String paramaters = "?llcommand=sndmsg&" + "ak=" + accessKey +   "&command=remoteinsert&" + dataSet;  
        String url = mobRemoteDB.baseUrlForRemoteInsert + paramaters;
        HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);    
        webRequest.Method = "POST";    
        webRequest.ContentType = "application/json";  
       if (NetworkInterface.GetIsNetworkAvailable() & IsDataValid)  
        {
         webRequest.BeginGetRequestStream(newAsyncCallback(GetRequestStreamCallback),webR equest); 
        }  
}  

void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;           
        webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);            
    }


 void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {                
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamResponse);
            JObject json_response = JObject.Parse(streamReader.ReadToEnd());
            String key = (String)json_response["ret"];
            JObject dic = (JObject)json_response["retdic"];
         }
         catch(WebException e)
         {
         }
    }

我希望RemoteInsert()方法等待我的回调GetResponseCallback。 我做了很多事情,我无法做到这一点 任何身体都可以在这里帮助我。 在此响应出现之前,我不希望主线程工作正常。 请建议。在响应之后我必须将它用于下一次执行。

Here My code is going like 
1. Task(A).running----await 
2.   ------------------------------->Task(B)
3                              ---------Response From Task(A)------->Task(C)

我希望像第一个任务A完成一样实现它,然后像任务(A)的成功一样实现任务(C)。然后任务(B)

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你想在调用线程上执行webrequest,并在继续之前等待它完成?

您可以使用async / await简化RemoteInsert()方法,并使用GetResponseAsync()方法在一次调用中获取响应对象。像这样:

public async Task RemoteInsert()
{
    String dataSet = "dataset=" + json.ToString();
    accessKey = mobRemoteDB.accessKey;
    String paramaters = "?llcommand=sndmsg&" + "ak=" + accessKey + "&command=remoteinsert&" + dataSet;
    String url = mobRemoteDB.baseUrlForRemoteInsert + paramaters;
    HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/json"; 

    if (NetworkInterface.GetIsNetworkAvailable() && IsDataValid)
    {
        // Await the GetResponseAsync() call.
        using(var response = await webRequest.GetResponseAsync().ConfigureAwait(false))
        {
            // The following code will execute on the main thread.
            using (var streamResponse = response.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(streamResponse))
                {
                    JObject json_response = JObject.Parse(streamReader.ReadToEnd());
                    String key = (String)json_response["ret"];
                    JObject dic = (JObject)json_response["retdic"];
                }
            }
        }
    }
}

并且失去了其他两种方法,因为它们不再需要。

当你调用这个方法时,可以对它进行Wait():

RemoteInsert().Wait();

然而,WP试图强制执行良好的异步模式以避免这样做。在这种情况下,您需要阻止UI线程吗?

在调用RemoteInsert()的方法中......假设它是某种按钮单击事件...你能不这样做吗?

public async void Button_Click()
{
    // First call Remote insert, and await the result.
    // The web-request will not block the UI thread.
    await RemoteInsert();

    // This code will be executed after RemoteInsert() completes:
    ... perform additional tasks that are dependant on RemoteInsert()
}

换句话说,不是阻止UI线程 - 而是在RemoteInsert()方法完成后执行其他方法。