一个简单的列子,需要把一个集合的数据添加到数据库中。
我先这样写了,然后报错了
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));//映射到一个可以遍历的taskawait 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" }));}