我是使用async修饰符进行异步编程的新手.我试图弄清楚如何确保我Main的控制台应用程序的方法实际上异步运行.
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = bs.GetList();
}
}
public class Bootstrapper {
public async Task<List<TvChannel>> GetList()
{
GetPrograms pro = new GetPrograms();
return await pro.DownloadTvChannels();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是从"顶部"异步运行的.由于无法async在Main方法上指定修饰符,如何在main异步中运行代码?
我试图在.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>'
任何帮助非常感谢.
我想异步制作一个Web服务请求.我在这里称呼它:
List<Item> list = GetListAsync();
Run Code Online (Sandbox Code Playgroud)
这是我的函数的声明,它应该返回一个列表:
private async Task<List<Item>> GetListAsync(){
List<Item> list = await Task.Run(() => manager.GetList());
return list;
}
Run Code Online (Sandbox Code Playgroud)
如果我想编译我得到以下错误
Cannot implicitely convert type System.Threading.Tasks.Task<System.Collections.Generic.List<Item>> to System.Collections.Generic.List<Item>
Run Code Online (Sandbox Code Playgroud)
据我所知,如果我使用async修饰符,结果将自动包含在Task中.我认为这不会发生,因为我使用Task.Run.如果我删除了Task.Run(() =>我得到的部分
无法等待System.Collections.Generic.List表达式
我想我还没有完全理解async/await方法.我做错了什么?