69

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<T>), I always get the same type of error error on the conversion back to T - which I understood was pretty much automatic. The following code produces the error:

Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.List<int>'

public List<int> TestGetMethod()
{
    return GetIdList(); // compiler error on this line
}


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;
    }
}

It fails if I explicitly cast the result as well. This:

public List<int> TestGetMethod()
{
    return (List<int>)GetIdList();  // compiler error on this line
}

somewhat predictably results in this error:

Cannot convert type 'System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.List<int>'

Any help greatly appreciated.

4

4 回答 4

99

您的示例的主要问题是您无法将Task<T>返回类型隐式转换为基本T类型。您需要使用 Task.Result 属性。请注意,Task.Result 将阻塞异步代码,应谨慎使用。

试试这个:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}
于 2013-06-04T23:17:31.500 回答
34

您还需要制作 TestGetMethodasync并在前面附加 awaitGetIdList();会将任务解包到List<int>,因此,如果您的辅助函数正在返回 Task ,请确保您在调用该函数时async也有 await 。

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;
    }
}

另外的选择

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}
于 2012-10-14T23:59:07.893 回答
3

根据您要执行的操作,您可以使用 GetIdList().Result 阻止(通常是一个坏主意,但很难说出上下文)或使用支持异步测试方法并让测试方法执行的测试框架var 结果 = 等待 GetIdList();

于 2012-10-14T21:42:55.317 回答
0

我刚刚弹出了同样的问题,但解决方案与其他问题不同。我正在使用异步方法中的两个异步调用,这段代码给了我错误:

var fileContents = reader.ReadToEndAsync();
if (fileContents != null)
{
     var profile = await Task.Run(() => JsonConvert.DeserializeObject<T>(fileContents));
     return profile;
}

这是修复。我忘记了第一行的异步:

var fileContents = await reader.ReadToEndAsync();
if (fileContents != null)
{
     var profile = await Task.Run(() => JsonConvert.DeserializeObject<T>(fileContents));
     return profile;
}

错误消息显示在 var profile = ... 行的“fileContents”上,因此并不能立即看出错误在哪里。

于 2022-01-20T18:42:41.117 回答