我正在尝试对某个服务器进行异步调用,以便主线程不会因请求而停止。
我创建了这样的请求:
//Create Request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = method;
request.ContentType = "application/XML";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
try
{
using (Stream requestStream = request.GetRequestStream())
{
// Send the data.
requestStream.Write(bytes, 0, bytes.Length);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
if (callback != null)
{
callback(response.GetResponseStream());
}
}
}, null);
}
catch (Exception ex)
{
//TODO: Log error
}
但是线程在此请求中仍然会停止一段时间。特别是在线上使用
(Stream requestStream = request.GetRequestStream())
我们有什么方法可以使它完全异步或其他更好的方式,以便我们的主线程不会挂起此请求。
答案 0 :(得分:1)
using (HttpClient client = new HttpClient())
{
var content = new StringContent(data, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(uri, content);
var respString = await response.Content.ReadAsStringAsync();
}
答案 1 :(得分:0)
需要使用异步方法并等待它们。
using (var stream = await request.GetRequestStreamAsync())
{
await stream.WriteAsync(bytes, 0, bytes.Length);
}
答案 2 :(得分:0)
这是一个简单的示例,我用它来制作异步请求。使用async keyword
using (var httpClient = new HttpClient())
{
string requestContent = string.Empty; // JSON Content comes here
HttpContent httpContent = new StringContent(requestContent, Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(Verb, url);
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequestMessage.Content = request.Verb == HttpMethod.Get ? null : httpContent;
response = httpClient.SendAsync(httpRequestMessage);
var responseContent = await response.Result.Content.ReadAsStringAsync();
}