实体框架Task.WhenAll不并行运行任务

时间:2018-10-06 00:35:35

标签: c# entity-framework asp.net-web-api

我正在尝试通过EF调用分离两种方法,并在完成后将它们组合在一起

            var startDate = StartDate;
            var endDate = EndDate;

            var middleDate = startDate.AddDays((endDate.Day) / 2);

            var db1 = new DbContext();
            var db2 = new DbContext();
            var responsePart1 =  GetAvailableCalendarDatesAndSlots(db1, startDate, middleDate);
            var responsePart2 =  GetAvailableCalendarDatesAndSlots(db2, middleDate.AddDays(1), endDate);
            await Task.WhenAll(responsePart1,responsePart2);
            var finalResponse = responsePart1.Result.Concat(responsePart2.Result).ToList();

但是,当我查看日志时,它们似乎不是并行运行的。 对于方法GetAvailableCalendarDatesAndSlots,由于日期范围较长,需要3秒才能完成任务。我打算尽可能将其降低到1.5秒。

如何使它们并行运行?

1 个答案:

答案 0 :(得分:0)

using System.Threading.Tasks;
class programe
{
 // db1, startDate, middleDate all should static variables
 private static R resdata;
 public  static async Task Main(string[] args)
 {
	Parallel.ForEach(GetSlots(db1, startDate, middleDate), async x =>
        {
		resdata.res += x;
	}

 }
 private static string GetSlots(db1, startDate, middleDate)
 {
	return GetAvailableCalendarDatesAndSlots(db1, startDate, middleDate);
 }	
}

public class R
{
public string res { get;set; }
}