在 C# 中使用 Web 服务:删除 Task.Wait()

Kid*_*per 2 c# task-parallel-library async-await dotnet-httpclient

我正在尝试使用 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; }
}
Run Code Online (Sandbox Code Playgroud)

}

nvo*_*igt 5

您已经处于async上下文中,因此只需使用await:

var stream = await response.Content.ReadAsStreamAsync();

using (var reader = new StreamReader(stream))
{
    responseValue = reader.ReadToEnd();
}
       
Run Code Online (Sandbox Code Playgroud)

也就是说,你应该检查你所有的电话:

HttpResponseMessage response = await client.GetAsync(url);
Run Code Online (Sandbox Code Playgroud)

并让您的main异步,同时我们在它使方法静态:

public static async Task Main)
{
    var result = await GetData();
}
Run Code Online (Sandbox Code Playgroud)

您的方法签名是:

public static async Task<string> GetData()
Run Code Online (Sandbox Code Playgroud)

这static不是必需的,但如果副作用尽可能少,您会发现并行和/或异步编程要容易得多。

  • 如果不解决的话,早期的“.Result”可能会导致问题。 (2认同)
  • @Olivier 是的,没有看到所有实例:) (2认同)