ForEach踩坑记

1

Api使用Furion时,使用了List.ForEach( acction())  action中Throw Bah.Oh(...) 

 

 1 [HttpGet]
 2 public async Task<int> ListForeach()
 3         { 
 4             string[] list = { "1", "2", "3" };
 5             list.ToList().ForEach(async x => {
 6                 if (x == "3")
 7                     await OtherFun(x);
 8                 Console.WriteLine(x); });    
 9 10 private async Task OtherFun(string id)
11         {
12                 throw Furion.FriendlyException.Oops.Bah("error");
13         }

2 void 返回值API

 [HttpGet]
        public void ListForeach()
        {
            DoThat that = new DoThat();
            that.Do();
        }

    interface DoSomethings
        {
            void Do();
        }

class DoThat : DoSomethings
        {
            public async void Do()
            {
                await Task.Run(() => throw Furion.FriendlyException.Oops.Oh("123"));
            }
        }

最开始以为是返回值的类型问题,后来发现是属同一个问题?什么问题,后面再写

问题就是出在 

list.ToList().ForEach(async ...)
这里的ForEach里面使用异步的原因
同样有一篇文章也提到了https://www.cnblogs.com/CreateMyself/p/13149429.html
也就是说目前可以理解成
.ForEach(async ...)的异步函数 不会产生同步效果。

 所以可以简单总结:

.ForEach(async ...)  等价于
  foreach (var item in collection)
            {
                Task.Run(() =>
                {
                    //xxxx
                });
            }

 

posted @ 2022-07-15 14:53  stweily  阅读(75)  评论(0编辑  收藏  举报