相关疑难解决方法(0)

无法在控制台应用程序的"Main"方法上指定"async"修饰符

我是使用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)

我知道这不是从"顶部"异步运行的.由于无法asyncMain方法上指定修饰符,如何在main异步中运行代码?

.net c# asynchronous console-application

415
推荐指数
10
解决办法
18万
查看次数

无法从Task <>隐式转换类型

我试图在.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>'

任何帮助非常感谢.

c# async-await

63
推荐指数
3
解决办法
9万
查看次数

从async/await方法返回列表

我想异步制作一个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方法.我做错了什么?

c# asynchronous list task async-await

25
推荐指数
4
解决办法
7万
查看次数

标签 统计

c# ×3

async-await ×2

asynchronous ×2

.net ×1

console-application ×1

list ×1

task ×1