C# foreach遇到async和await
标签:names info stat sel img 集合 lam type color
一个简单的列子,需要把一个集合的数据添加到数据库中。
我先这样写了,然后报错了
public async Task Test([FromUri]string name = "")
{
Liststring> strList = new Liststring>() { "测试", "测试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 Test([FromUri]string name = "")
{
Liststring> strList = new Liststring>() { "测试", "测试1", "测试2", "测试3", "测试4", "测试5", "测试6", "测试7", "测试8" };
IEnumerable tasks = strList.Select(x => TestAsync(x));//映射到一个可以遍历的task
await Task.WhenAll(tasks); //使用task.whenall 完成
return await Task.FromResult(Ok(new { errcode = 0, errmag = "success" }));
}
///
/// 根据传入的名称,返回需要执行的task代码
///
///
///
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);
}
}
②扩展方法,一个个的执行
///
/// 使用异步遍历处理数据
///
/// 需要遍历的基类
/// 集合
/// Lambda表达式
///
public static async Task ForEachAsync(this List list, Func func)
{
foreach (T value in list)
{
await func(value);
}
}
public async Task Test([FromUri]string name = "")
{
Liststring> strList = new Liststring>() { "测试", "测试1", "测试2", "测试3", "测试4", "测试5", "测试6", "测试7", "测试8" };
//①先得到集合,然后一起执行
//IEnumerable tasks = strList.Select(x => TestAsync(x));//映射到一个可以遍历的task
//await Task.WhenAll(tasks); //使用task.whenall 完成
//②一步一步的循环
await strList.ForEachAsyncstring>(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
标签:names info stat sel img 集合 lam type color
原文地址:https://www.cnblogs.com/Sea1ee/p/10624769.html
评论