代码改变世界

Task 小记

2018-09-22 16:45  音乐让我说  阅读(220)  评论(0编辑  收藏  举报

1. 注意 Task 执行的顺序。

如下代码:

 1             IQueryable<T> querySet;
 2             if (preConditionExpression == null)
 3             {
 4                 querySet = Table; // 原来是 TableWhereUnDeleted
 5             }
 6             else
 7             {
 8                 querySet = Table.Where(preConditionExpression); //原来是 TableWhereUnDeleted.Where(preConditionExpression); 
 9             }
10             if (conditionCombined != null && condition != null)
11             {
12                 querySet = conditionCombined(querySet, condition);
13             }
14             int recordCount = await querySet.CountAsync();
15             querySet = SkipAndTakeInternal(querySet, skip, take, orderKeySelector);
16             var list = await querySet.ToListAsync();
17             return new LightPagedList<T>()
18             {
19                 DataList = list,
20                 RecordCount = recordCount
21             };

这个方法有一个问题,就是第 15 行没有 await,这样执行的时候有一个 BUG,其实第 14 行和第 15 行几乎是同时执行,虽然第 14 行有一个 await,但仅仅是把第 14 行的返回值赋值给 int recordCount,而第 15 行同时执行了,导致最终 LightPagedLIst 的 DataList 为 NULL。

还有一个问题,切记不要把 LightPagedList 放到匿名方法体以内,那样  LightPagedList  始终得不到值。

推荐如下代码:

 1             IQueryable<T> querySet;
 2             if (preConditionExpression == null)
 3             {
 4                 querySet = Table; // 原来是 TableWhereUnDeleted
 5             }
 6             else
 7             {
 8                 querySet = Table.Where(preConditionExpression); //原来是 TableWhereUnDeleted.Where(preConditionExpression); 
 9             }
10             if (conditionCombined != null && condition != null)
11             {
12                 querySet = conditionCombined(querySet, condition);
13             }
14             LightPagedList<T> result = new LightPagedList<T>();
15             Task<int> task1 = querySet.CountAsync();
16             result.RecordCount = await task1;
17             Task<IQueryable<T>> task2 = task1.ContinueWith<IQueryable<T>>(t =>
18             {
19                 return SkipAndTakeInternal(querySet, skip, take, orderKeySelector);
20             });
21             result.DataList = await task2.ContinueWith(t =>
22             {
23                 return t.Result.ToListAsync();
24             }).Result;
25             return result;

 

谢谢浏览!