C# 等待HttpWebRequest.BeginGetRequestStream的结束
我正在尝试使用C# 等待HttpWebRequest.BeginGetRequestStream的结束,c#,multithreading,C#,Multithreading,我正在尝试使用HttpWebRequest.BeginGetRequestStream方法。在我的方法中,我得到了一些Json。我需要等待此方法的结束(HttpWebRequest.BeginGetRequestStream)来分析我的Json 这是我的密码: private string API_Query(string url) { HttpWebRequest requete = (HttpWebRequest)HttpWebRequest.Create(url); req
HttpWebRequest.BeginGetRequestStream
方法。在我的方法中,我得到了一些Json
。我需要等待此方法的结束(HttpWebRequest.BeginGetRequestStream)
来分析我的Json
这是我的密码:
private string API_Query(string url)
{
HttpWebRequest requete = (HttpWebRequest)HttpWebRequest.Create(url);
requete.Method = "POST";
requete.ContentType = "application/x-www-form-urlencoded";
requete.BeginGetRequestStream(DebutReponse, requete);//wait the end of this method
//analyse the json here
return null;
}
问题是我不知道如何等待方法的结束。我尝试了不同的方法,比如任务和线程,但我不确定如何正确地执行
谢谢你的帮助
问题是我不知道如何等待方法的结束
有很多方法可以做到这一点。在我看来,您希望同步调用请求,因此我建议您只需调用GetResponseStream
:
private string ApiQuery(string url)
{
HttpWebRequest requete = (HttpWebRequest)HttpWebRequest.Create(url);
requete.Method = "POST";
requete.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = requete.GetRequestStream())
{
// Write to request stream
}
using (var responseStream = requete.GetResponse())
{
// Read the respone stream, parsing out your JSON.
}
}
编辑:
正如您在评论中提到的,这是一个Silverlight项目。这意味着您没有同步版本的HttpWebRequest
。相反,您可以使用WebClient
:
var webClient = new WebClient()
webClient.OpenReadCompleted += OnUploadCompleted;
webClient.OpenReadAsync(url, data);
private void OnUploadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
// Error, do something useful
return;
}
using (var responseStream = e.Result)
{
byte[] data = (byte[]) e.UserState;
// Read response from stream.
}
}
如果请求是异步执行的,这对您有关系吗?因为这就是它对
BeginGetRequestStream
所做的。是的,我更喜欢这样,因为应用程序不会冻结。但是,如果您有一个异步执行的解决方案,我可以使用线程after来异步执行。*同步我的意思是我只是尝试了一下,但没有找到方法requete.GetRequestStream()。我只是有requete.BeginGetRequestStream(),是一样的吗?可能是因为我在做一个Silverlight应用程序,我不知道,或者我的项目是break lol。