C#async不等待

Den*_*nie -1 c# json asynchronous task async-await

我正在处理的应用程序应该使用http客户端检索json字符串,然后在应用程序中进行反序列化并使用它.

一切正常,除了等待功能.我做错了什么,我似乎无法弄清楚是什么.我如何确保我的DataService类等待,直到我有我的json并且它已被反序列化?

DataService类:

class DataService : IDataService
{
    private IEnumerable<Concert> _concerts;

    public DataService()
    {
        _concerts = new DataFromAPI()._concerts;

        Debug.WriteLine("____Deserialization should be done before continuing____");

        **other tasks that need the json**

    }
}
Run Code Online (Sandbox Code Playgroud)

我的http客户端类:

class DataFromAPI
{

    public IEnumerable<Concert> _concerts { get; set; }

    public DataFromAPI()
    {
        Retrieve();
    }

    public async Task Retrieve()
    {
        try
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            var result = await client.GetAsync(new Uri("http://url-of-my-api"), HttpCompletionOption.ResponseContentRead);
            string jsonstring = await result.Content.ReadAsStringAsync();
            DownloadCompleted(jsonstring);
        }
        catch {}

    }

    void DownloadCompleted(string response)
    {
        try
        {
            _concerts = JsonConvert.DeserializeObject<IEnumerable<Concert>>(response.ToString());

        }
        catch {}
    }
}
Run Code Online (Sandbox Code Playgroud)

经过大量的试验和错误,我意识到,对于这个特殊的东西,它不必是异步的,所以我只是在主线程上重新创建,并成功:

DataService类:

class DataService : IDataService
{
    private IEnumerable<Concert> _concerts;

    public DataService()
    {
        _concerts = new DataFromAPI()._concerts;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的http客户端类:

public static class DataFromAPI
{ 
    public void Retrieve()
    {
        try
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            var result = client.GetAsync("http://url-of-my-api").Result;
            if (result.IsSuccessStatusCode)
            {
                var responseContent = result.Content;   
            }
            DownloadCompleted(result.Content.ReadAsStringAsync().Result);
        }
        catch {}
    }
}
Run Code Online (Sandbox Code Playgroud)

rdu*_*com 6

Retrieve()没有 awaitDataFromAPI构造函数中调用,这就是为什么不等待你的方法.

您最好在构造函数之外调用此方法,使用如下的await关键字:

await Retrieve();
Run Code Online (Sandbox Code Playgroud)

你必须稍微重构你的代码.这是一个例子:

public class DataService : IDataService
{
    private IEnumerable<Concert> _concerts;

    public async Task LoadData()
    { 
        _concerts = await DataFromAPI.Retrieve();
        **other tasks that need the json**
    }
}

public static class DataFromAPI
{ 
    public static async Task<IEnumerable<Concert>> Retrieve()
    {
        try
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            var result = await client.GetAsync(new Uri("http://url-of-my-api"), HttpCompletionOption.ResponseContentRead);
            string jsonstring = await result.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<IEnumerable<Concert>>(response.ToString());
        }
        catch(Exception)
        {
        }
        return Enumerable.Empty<Concert>();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当你创建DataService实例时,就在你必须调用它的LoadData()方法之后.

DataService ds = new DataService();
await ds.LoadData();
Run Code Online (Sandbox Code Playgroud)

当然,还必须从异步方法调用这两行代码.(异步/等待一路)