我的网络服务响应时间非常慢,这是我第一次使用Async / await选项但不确定它是否正确。如果我直接查询表,它只需要大约3秒。但现在需要更长的时间。
我想要做的是找出哪些程序被激活(可见给用户),并在第一步中加载ProgramCode,ReleaseDate和ProgramMetadata表获取ProgramName(包括:系列选项,做一些合并)其余的可以加载后。这实际上是否可行,如果可行,我需要做些什么改变才能实现这个目标?我附上了网络服务代码:
[Route("Programs/{id_activation_state}")]
public async Task<HttpResponseMessage> GetProgramByActivationState(int id_activation_state)
{
List<Program> ListPrograms = new List<Program>();
foreach (var item in await db.Program.Where(p => p.id_program_activationState == id_activation_state).OrderBy(pg => pg.ProgramCode).ToListAsync())
{
Program programReturned = new Program();
programReturned.id_program = item.id_program;
programReturned.ReleaseDate = item.ReleaseDate;
programReturned.ProgramCode = item.ProgramCode;
programReturned.Duration = item.Duration;
programReturned.ImdbCode = item.ImdbCode;
programReturned.id_program_rating = item.id_program_rating;
programReturned.id_program_activationState = item.id_program_activationState;
programReturned.DefaultLanguage = item.DefaultLanguage;
programReturned.ProgramType = item.ProgramType;
programReturned.ListingGenre = item.ListingGenre;
programReturned.ListingGenre1 = item.ListingGenre1;
programReturned.ListingGenre2 = item.ListingGenre2;
if (item.ProgramMetadata.Count > 0)
{
ProgramMetadata PM = new ProgramMetadata();
PM = item.ProgramMetadata.Where(pm => pm.id_language == item.DefaultLanguage).FirstOrDefault();
PM.ProgramActivationState = null;
if (item.ProgramType == 3)
{
var query = from ps in db.ProgramSerie
join pss in db.ProgramSerieSeason on ps.id_program_serie equals pss.id_program_serie
join pse in db.ProgramSerieEpisode on pss.id_program_serie_season equals pse.id_program_season
where pse.id_program == item.id_program
select new
{
SerieName = ps.SerieName,
Season = pss.SeasonNumber,
Episode = pse.EpisodeNumber
};
if (query.Count() > 0)
PM.ProgramName = query.First().SerieName.Trim() + ": " + PM.ProgramName.Trim() + ", S" + query.First().Season + "E" + query.First().Episode;
}
programReturned.ProgramMetadata.Add(PM);
}
ListPrograms.Add(programReturned);
}
return Request.CreateResponse(HttpStatusCode.OK, new { Program = ListPrograms });
}
答案 0 :(得分:0)
Await和Async运行代码不并行它只是不阻塞主线程。这样UI就可以绘制了。但在控制器需要其他东西。你可以尝试Parallel.For ... MSDN Parallel for
但我认为您应该重新考虑您的架构。呼叫被阻止,直到查询结束。更好的是你发送请求并离开控制器方法。在后台线程中运行查询,最后通过signalR发送答案......