[英]Consume a Web Service in C#: Remove Task.Wait()
我正在嘗試使用 web 服務。 這是一個基於 XML 的服務。 我的意思是 XML 格式的響應。 代碼工作正常。 但是,我不想使用 task.Wait()。 請讓我知道如何用 async/await 替換它。
下面是我的代碼:
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
var result = obj.GetData().Result;
}
public async Task<string> GetData()
{
string url =
"https://test.net/info.php?akey=abcd&skey=xyz";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url).Result;
var responseValue = string.Empty;
if (response != null)
{
Task task = response.Content.ReadAsStreamAsync().ContinueWith(t =>
{
var stream = t.Result;
using (var reader = new StreamReader(stream))
{
responseValue = reader.ReadToEnd();
}
});
task.Wait(); // How I can replace it and use await
}
return responseValue;
}
}
[XmlRoot(ElementName = "Info")]
public class Test
{
[XmlAttribute(AttributeName = "att")]
public string SomeAttribute{ get; set; }
[XmlText]
public string SomeText{ get; set; }
}
}
您已經處於async
上下文中,因此只需使用await
:
var stream = await response.Content.ReadAsStreamAsync();
using (var reader = new StreamReader(stream))
{
responseValue = reader.ReadToEnd();
}
也就是說,您應該檢查所有電話:
HttpResponseMessage response = await client.GetAsync(url);
並讓你的main
異步,當我們在它做方法static:
public static async Task Main)
{
var result = await GetData();
}
您的方法簽名在哪里:
public static async Task<string> GetData()
static
不是必需的,但如果副作用盡可能少,您會發現並行和/或異步編程要容易得多。
您也可以使Main
方法async
並await
GetData
static async Task Main(string[] args)
{
Program obj = new Program();
var result = await obj.GetData();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.