Cannot implicitly convert type from Task<>

后端 未结 3 721
逝去的感伤
逝去的感伤 2020-12-01 08:56

I am trying to master async method syntax in .NET 4.5. I thought I had understood the examples exactly however no matter what the type of the async method is (ie Task

相关标签:
3条回答
  • 2020-12-01 09:27

    The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

    Try this instead:

    public List<int> TestGetMethod()  
    {  
        return GetIdList().Result;  
    }
    
    0 讨论(0)
  • 2020-12-01 09:27

    Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

    0 讨论(0)
  • 2020-12-01 09:37

    You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

    public Task<List<int>> TestGetMethod()
    {
        return GetIdList();
    }    
    
    async Task<List<int>> GetIdList()
    {
        using (HttpClient proxy = new HttpClient())
        {
            string response = await proxy.GetStringAsync("www.test.com");
            List<int> idList = JsonConvert.DeserializeObject<List<int>>();
            return idList;
        }
    }
    

    Another option

    public async void TestGetMethod(List<int> results)
    {
        results = await GetIdList(); // await will unwrap the List<int>
    }
    
    0 讨论(0)
提交回复
热议问题