【问题标题】:console application async/await not returning my list控制台应用程序异步/等待不返回我的列表
【发布时间】:2019-03-01 12:21:44
【问题描述】:

为什么下面的代码不能编译?我只是想得到一个简单的列表来返回。

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

【问题讨论】:

  • 你得到什么编译错误?
  • 为什么await在return语句中?
  • 更新了带有编译错误的代码。异步/等待的新手,所以我只是尝试一些简单的东西来尝试理解。
  • MainAsync 不返回值。你为什么要在这里将结果存储到list

标签: c# async-await


【解决方案1】:

这里没有用例来制作这个方法async,只返回一个List&lt;string&gt;

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

但是,如果您需要在 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;
}

更新

或者模拟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);
}

更新

正如 Rufo 爵士所提到的,asyncawait 有很多内容,最好从 Stephen Cleary 开始,他是一个非常善于表达此类主题的博主

【讨论】:

  • 我只是想模拟一个会填充列表的数据库调用
  • 因为 OP 是 async/await 的新手,你应该提到 ConfigureAwait(false) 否则你会让他陷入未来的死锁
  • @Rod 阅读blog of Stephen Cleary,你会发现很多异步/等待
  • ConfigureAwait(false) 仅当您在 UI 同步上下文(也是 asp.net 请求上下文)中触发任务时才需要,因为默认情况下所有工作都安排在 UI 线程上。控制台应用程序不会有这个问题,因为它会在线程池线程上安排任务。我也会推荐 Cleary 的这本书:amazon.com/…
猜你喜欢
  • 2023-03-04
  • 2019-07-20
  • 1970-01-01
  • 2019-07-22
  • 2021-04-03
  • 1970-01-01
  • 2020-03-13
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多