C# foreach遇到async和await

一個簡單的列子,須要把一個集合的數據添加到數據庫中。數據庫

我先這樣寫了,而後報錯了異步

     public async Task<IHttpActionResult> Test([FromUri]string name = "")
        {
            List<string> strList = new List<string>() { "測試", "測試1", "測試2", "測試3", "測試4", "測試5", "測試6", "測試7", "測試8" };
            strList.ForEach(async x =>
            {
                JkSystemname jk = await dbOracle.JkSystemnames.AsQueryable().FirstAsync(ee => ee.Name == x);
                if (jk == null)
                {
                    jk = new JkSystemname() { Name = x };
                    dbOracle.JkSystemnames.Insert(jk);
                }
            });
            return await Task.FromResult(Ok(new { errcode = 0, errmag = "success" }));
        }

 

兩個辦法解決循環裏面不能使用異步async

①把方法提出來,而後返回task,而後一塊兒執行,這樣不會按順序執行測試

 public async Task<IHttpActionResult> Test([FromUri]string name = "")
        {
            List<string> strList = new List<string>() { "測試", "測試1", "測試2", "測試3", "測試4", "測試5", "測試6", "測試7", "測試8" };
            IEnumerable<Task> tasks = strList.Select(x => TestAsync(x));//映射到一個能夠遍歷的task
            await Task.WhenAll(tasks);  //使用task.whenall 完成
            return await Task.FromResult(Ok(new { errcode = 0, errmag = "success" }));
        }

        /// <summary>
        /// 根據傳入的名稱,返回須要執行的task代碼
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task TestAsync(string name)
        {
            JkSystemname jk = await dbOracle.JkSystemnames.AsQueryable().FirstAsync(ee => ee.Name == name);
            if (jk == null)
            {
                jk = new JkSystemname() { Name = name };
                dbOracle.JkSystemnames.Insert(jk);
            }
        }

 

 

 

②擴展方法,一個個的執行this

 /// <summary>
        /// 使用異步遍歷處理數據
        /// </summary>
        /// <typeparam name="T">須要遍歷的基類</typeparam>
        /// <param name="list">集合</param>
        /// <param name="func">Lambda表達式</param>
        /// <returns></returns>
        public static async Task ForEachAsync<T>(this List<T> list, Func<T, Task> func)
        {
            foreach (T value in list)
            {
                await func(value);
            }
        }
 public async Task<IHttpActionResult> Test([FromUri]string name = "")
        {
            List<string> strList = new List<string>() { "測試", "測試1", "測試2", "測試3", "測試4", "測試5", "測試6", "測試7", "測試8" };
            //①先獲得集合,而後一塊兒執行
            //IEnumerable<Task> tasks = strList.Select(x => TestAsync(x));//映射到一個能夠遍歷的task
            //await Task.WhenAll(tasks);  //使用task.whenall 完成
            //②一步一步的循環
            await strList.ForEachAsync<string>(async x =>
            {
                JkSystemname jk = await dbOracle.JkSystemnames.AsQueryable().FirstAsync(ee => ee.Name == x);
                if (jk == null)
                {
                    jk = new JkSystemname() { Name = x };
                    dbOracle.JkSystemnames.Insert(jk);
                }
            });
           
            return await Task.FromResult(Ok(new { errcode = 0, errmag = "success" }));
        }

相關文章
相關標籤/搜索