将方法放入任务中以避免阻塞 asp.net 线程
我想知道以下代码在网络服务器上运行时是否有我不知道的问题。阅读优秀系列http://reedcopsey.com/series/parallelism-in-net4/< /a> 我无法找到任何与我的问题具体相关的内容,与 msdn 相同,所以我想我应该把它带到这里。
调用示例:
public ActionResult Index() {
ViewBag.Message = "Welcome to ASP.NET MVC!";
Task.Factory.StartNew(() => {
//This is some long completing task that I don't care about
//Say logging to the database or updating certain information
System.Threading.Thread.Sleep(10000);
});
return View();
}
I'm wondering if the following code has any gotcha's that I'm not aware of when running on a webserver. Reading through the excellent series http://reedcopsey.com/series/parallelism-in-net4/ I am unable to find anything that relates specifically to my question, same with the msdn, so I thought I'd bring it here.
Example call:
public ActionResult Index() {
ViewBag.Message = "Welcome to ASP.NET MVC!";
Task.Factory.StartNew(() => {
//This is some long completing task that I don't care about
//Say logging to the database or updating certain information
System.Threading.Thread.Sleep(10000);
});
return View();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ASP.Net支持异步页面,参见ASP.NET中的异步页面,但是编程比较复杂模型并且完全不与 MVC 绑定。话虽这么说,从同步请求处理程序启动异步任务在一定程度上是有效的:
ASP.Net supports asynchronous pages, see Asynchronous Pages in ASP.NET, but is a complicated programming model and does not bind at all with MVC. That being said, launching asynchronous tasks from a synchronous requests handler works up to a point:
在这种情况下,一件重要的事情是确保任务中包含的代码包装在 try/catch 块中,否则该线程中抛出的任何可能的异常都会传播。您还应该确保在此长时间运行的任务中,您不会访问任何 Http Context 成员,例如请求、响应、会话...,因为当您访问它们时它们可能不再可用。
One important thing in this case is to ensure that the code contained inside the task is wrapped in a try/catch block or any possible exceptions thrown in this thread will propagate. You also should ensure that in this long running task you are not accessing any of the Http Context members such as Request, Response, Session, ... as they might no longer be available by the time you access them.
使用
new Thread
而不是Task.Factory.StartNew
。Task.Factory.StartNew
使用线程池中的线程,如果您有许多后台任务,线程池将耗尽线程并降低您的 Web 应用程序的性能。请求将排队,您的 Web 应用程序最终将终止:)您可以使用 Thread.CurrentThread.IsThreadPoolThread 测试您的后台工作是否在线程池上执行。如果得到 True,则使用线程池。
Use
new Thread
instead ofTask.Factory.StartNew
.Task.Factory.StartNew
use thread from Threads Pool and if you will have many background tasks a Threads Pool will run out of threads and will degrade your web application. The requests will be queued and your web app eventually will die :)You can test is your background work executed on Thread Pool using
Thread.CurrentThread.IsThreadPoolThread
. If you get True then Thread Pool is used.