我在ASP.NET MVC 3应用程序中有一个搜索操作,它返回包含给定关键字的建议和建议:
[HttpPost] public ActionResult Search(string query,int pg = 0) { var keywords = query.Split(new[] { ' ',',';' },StringSplitOptions.RemoveEmptyEntries); var containing = (from s in _readonlySession.All<Suggestion>() from k in keywords where (s.Text.ToLower().Contains(k.ToLower())) orderby s.Text select s).Distinct(); var tagged = (from t in _readonlySession.All<Tag>() from s in t.Suggestions from k in keywords where t.Text.ToLower().Contains(k.ToLower()) orderby s.Text select s).Distinct(); var model = new Searchviewmodel { Query = query,Containing = containing.ToList(),Tagged = tagged.ToList() }; return View(model); }
解决方法
任务Parallels库是您的最佳选择.通过Google获取大量信息,但下面是您的实施可能的样子.
[HttpPost] public ActionResult Search(string query,StringSplitOptions.RemoveEmptyEntries); IEnumerable containing=null; Task t1 = Task.Factory.StartNew(() => { containing = (from s in _readonlySession.All<Suggestion>() from k in keywords where (s.Text.ToLower().Contains(k.ToLower())) orderby s.Text select s).Distinct().ToList(); }); IEnumerable tagged=null; Task t2 = Task.Factory.StartNew(() => { var tagged = (from t in _readonlySession.All<Tag>() from s in t.Suggestions from k in keywords where t.Text.ToLower().Contains(k.ToLower()) orderby s.Text select s).Distinct().ToList(); }); t1.Wait(); t2.Wait(); var model = new Searchviewmodel { Query = query,Tagged = tagged.ToList() }; return View(model); }
请记住,如果您的应用程序收到大量请求,您可能最好不要异步执行查询 – 消耗2个额外的线程来为一个请求提供服务会使资源远离其他传入请求.如果您有大量流量,或者您的硬件不合适,这只会是一个问题.