1. 程式人生 > >C# foreach遇到async和await

C# foreach遇到async和await

lec lam summary 技術 ima clas public 表達 不能

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

我先這樣寫了,然後報錯了

     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" })); }

技術分享圖片

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

①把方法提出來,然後返回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); } }

技術分享圖片

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

 /// <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" }));
        }

技術分享圖片

C# foreach遇到async和await