当前位置: 移动技术网 > IT编程>开发语言>.net > List<T>.ForEach 调用异步方法的意外

List<T>.ForEach 调用异步方法的意外

2019年01月17日  | 移动技术网IT编程  | 我要评论
有这么个异步方法 private static async Task Compute(int s) { return await Task.Run(() = { if (s s = new List { 1, 2, 3, 4, 5 }; List t = new List(); s.ForEach( ...

有这么个异步方法

 private static async task<int> compute(int s)
    {
        return await task<int>.run(() =>
        {
            if (s < 5)
                return s * 2;
            else
                return s * 3;
        });

    }

当然实际过程是从数据库获取或者从网络上获取什么内容。

现在我想调用:

    private static void main(string[] args)
    {
        list<int> s = new list<int> { 1, 2, 3, 4, 5 };
        list<int> t = new list<int>();
        s.foreach(ii =>
        {
            int ret = await compute(ii);
            t.add(ret);
        });

        t.foreach(ii => console.writeline(ii));
    }

发现 vs 划了一条下划线

ok,await 必须 async的,简单,改一下

    private static void main(string[] args)
    {
        list<int> s = new list<int> { 1, 2, 3, 4, 5 };
        list<int> t = new list<int>();
        s.foreach(async ii =>
        {
            int ret = await compute(ii);
            t.add(ret);
        });

        t.foreach(ii => console.writeline(ii));
    }

然后,ctrl+f5运行,报错了!

错误在

        t.foreach(ii => console.writeline(ii));

原因在:foreach 调用了一个 async void 的action,没有await(也没法await,并且await 没返回值的也要设成task,没法设)
老老实实改成 foreach(var ii in s)。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网