简体   繁体   English

控制台应用程序 async/await 不返回我的列表

[英]console application async/await not returning my list

Why doesn't the following compile?为什么以下不编译? I'm just trying to get a simple list to return.我只是想得到一个简单的列表来返回。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = MainAsync(args).Wait();
            //Compile error: Cannot assign void to an implicitly-typed variable
        }

        static async Task MainAsync(string[] args)
        {
            Bootstrapper bs = new Bootstrapper();
            var list = await bs.GetList();
        }
    }

    public class Bootstrapper
    {
        public async Task<List<string>> GetList()
        {
            List<string> toReturn = new List<string>();
            toReturn.Add("hello");
            toReturn.Add("world");
            return await toReturn;
            //Compile error: 'List<string>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'List<string>'
        }
    }
}

There is no use case here to make this method async , just return a List<string>这里没有使此方法async用例,只需返回一个List<string>

public List<string> GetList()
{
    List<string> toReturn = new List<string>();
    toReturn.Add("hello");
    toReturn.Add("world");
    return toReturn;
}

However, if there were some IO or otherwise async calls you needed to make in GetList , then you could do the following但是,如果您需要在GetList进行一些IO或其他async调用,则可以执行以下操作

public async Task<List<string>> GetList()
{
    // now we have a reason to be async (barely)
    await Task.Delay(1000);
    List<string> toReturn = new List<string>();
    toReturn.Add("hello");
    toReturn.Add("world");
    return toReturn;
}

Update更新

or another way to simulate an async workload is Task.FromResult或另一种模拟async工作负载的方法是Task.FromResult

private async Task<List<string>> Test()
{
    List<string> toReturn = new List<string>();
    toReturn.Add("hello");
    toReturn.Add("world");
    return await Task.FromResult(toReturn);
}

Update更新

As mentioned by Sir Rufo, there is a lot to this async and await a good place to start is with Stephen Cleary , he is a very well articulated blogger on such topics正如 Rufo 爵士提到的,这个async有很多东西, await一个好的起点是Stephen Cleary ,他是一个关于这些主题的非常清晰的博主

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM