Error with await operator

前端 未结 2 736
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 15:41

There is problem with my code. How can I solve this problem? This problem in await operator.

 public MyModel() 
    {
        HttpClient client = new HttpClient(         


        
相关标签:
2条回答
  • 2021-01-29 15:59

    You can't use await in the constructor of a class.

    An async method returns a Task object which can be executed async. A constructor does not have a return type and thus can't return a Task object, and thus can't be awaited.

    A simple fix for this problem is create a Init function:

    public MyModel() 
    {
    
    }
    
    public async Task Init()
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637143e318cc79e826149");
        string googleSearchText = await response.Content.ReadAsStringAsync();
        JObject googleSearch = JObject.Parse(googleSearchText);
        IList<JToken> results = googleSearch["response"].Children().Skip(1).ToList();
        IList<MainPage1> searchResults = new List<MainPage1>();
        foreach (JToken result in results)
        {
            MainPage1 searchResult = JsonConvert.DeserializeObject<MainPage1>(result.ToString());
            searchResults.Add(searchResult);
    
        }
    }
    

    Then when you create your model:

    var model = new MyModel();
    await model.Init();
    
    0 讨论(0)
  • 2021-01-29 16:09

    You're trying to use await within a constructor. You can't do that - constructors are always synchronous.

    You can only use await within a method or anonymous function with the async modifier; you can't apply that modifier to constructors.

    One approach to fixing this would be to create a static async method to create an instance - that would do all the relevant awaiting, and then pass the results to a simple synchronous constructor. Your callers would then need to handle this appropriately, of course.

    public static async Task<MyModel> CreateInstance()
    {
        string googleSearchText;
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(...))
            {
                googleSearchText = await response.Content.ReadAsStringAsync();
            }
        }
        // Synchronous constructor to do the rest...
        return new MyModel(googleSearchText);
    }
    
    0 讨论(0)
提交回复
热议问题