我试图在.NET 4.5中掌握异步方法语法.我以为我已经明白了究竟例子然而无论异步方法的类型是什么(即Task<T>),我总是得到相同类型的错误错误的转换回T-我明白这是相当多的自动.以下代码生成错误:
无法隐式将类型'
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为'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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我显式地转换结果,它也会失败.这个:
public List<int> TestGetMethod()
{
return (List<int>)GetIdList(); // compiler error on this line
}
Run Code Online (Sandbox Code Playgroud)
有点可以预见会导致此错误:
无法将类型'
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为'System.Collections.Generic.List<int>'
任何帮助非常感谢.
use*_*853 86
您的示例的主要问题是您无法将Task<T>返回类型隐式转换为基T类型.您需要使用Task.Result属性.请注意,Task.Result将阻止异步代码,应谨慎使用.
试试这个:
public List<int> TestGetMethod()
{
return GetIdList().Result;
}
Run Code Online (Sandbox Code Playgroud)
May*_*ank 29
你需要制作TestGetMethod async并在前面附加await GetIdList();将List<int>你的任务解包到,所以如果你的帮助函数正在返回任务,请确保你等待调用该函数async.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
另外一个选项
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}
Run Code Online (Sandbox Code Playgroud)
根据您想要执行的操作,您可以使用 GetIdList().Result 进行阻止(通常是一个坏主意,但很难分辨上下文)或使用支持异步测试方法并让测试方法执行的测试框架var 结果 = 等待 GetIdList();