如何使用streamreader调用异步WebResponse以等待响应c#

时间:2014-12-23 07:17:16

标签: c# asynchronous streamreader webresponse

我必须重构此代码以使用异步。我从不使用它,我不知道该怎么做。 使用该代码的服务器必须等待响应 - 现在在exec之后CallRequestSend服务器不等待响应。我必须等待soapResult。 请帮助。

private string CallRequestSend (MemoryStream RequestStream)
{
    string xmleek = Encoding.ASCII.GetString(RequestStream.ToArray());
    StringBuilder sb = new StringBuilder(xmleek);
    sb[0] = '$';
    sb[1] = '$';
    sb[2] = '$';
    xmleek = sb.ToString();
    xmleek = xmleek.Replace("$", string.Empty);//must do it
    string soapResult = "";    
    XmlDocument soapEnvelopeXml = new XmlDocument();
    try
    {
        soapEnvelopeXml.LoadXml(xmleek);
    }
    catch (Exception x)
    {

    }
    HttpWebRequest request = CreateWebRequest();
    using (Stream stream = request.GetRequestStream())
    {
        soapEnvelopeXml.Save(stream);
    }
    using (WebResponse response = request.GetResponse())
    {
        using (StreamReader rd = new StreamReader(response.GetResponseStream()))
    {

    soapResult = rd.ReadToEnd();
    }
}
return soapResult;
}

public HttpWebRequest CreateWebRequest()
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(soapurl);
    webRequest.Headers.Add(@"SOAP:Action");
    webRequest.ContentType = "text/xml;charset=\"utf-8\"";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    return webRequest;
}

0 个答案:

没有答案