Ala*_*ala 5 c# async-await win-universal-app
我想从通用 Windows Phone 应用程序中的 JSON 文件进行解析,但我无法将任务转换为字符串
public MainPage()
{
this.InitializeComponent();
HttpClient httpClient = new HttpClient();
String responseLine;
JObject o;
try
{
string responseBodyAsText;
HttpResponseMessage response = httpClient.GetAsync("http://localhost/list.php").Result;
//response = await client.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
responseBodyAsText = response.Content.ReadAsStringAsync().Result;
// responseLine = responseBodyAsText;
string Website = "http://localhost/list.php";
Task<string> datatask = httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks)));
string data = await datatask;
o = JObject.Parse(data);
Debug.WriteLine("firstname:" + o["id"][0]);
}
catch (HttpRequestException hre)
{
}
Run Code Online (Sandbox Code Playgroud)
我在这一行有错误
string data = await datatask;
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
小智 14
查看此文档,您可以使用:Result 属性来获取该信息。
例如:
Task<int> task1 = myAsyncMethod(); //You can also use var instead of Task<int>
int i = task1.Result;
Run Code Online (Sandbox Code Playgroud)
await您不能在构造函数内部使用。您需要async为此创建一个方法。
一般来说,我不建议使用async void,但是当您从构造函数中调用它时,这是有道理的。
public MainPage()
{
this.InitializeComponent();
this.LoadContents();
}
private async void LoadContents()
{
HttpClient httpClient = new HttpClient();
String responseLine;
JObject o;
try
{
string responseBodyAsText;
HttpResponseMessage response = await httpClient.GetAsync("http://localhost/list.php");
//response = await client.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
responseBodyAsText = await response.Content.ReadAsStringAsync();
// responseLine = responseBodyAsText;
string Website = "http://localhost/list.php";
Task<string> datatask = httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks)));
string data = await datatask;
o = JObject.Parse(data);
Debug.WriteLine("firstname:" + o["id"][0]);
}
catch (HttpRequestException hre)
{
// You might want to actually handle the exception
// instead of silently swallowing it.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24525 次 |
| 最近记录: |