简体   繁体   English

从ASP.NET启动和停止线程

[英]starting and stopping threads from ASP.NET

I have to start a thread to do some long running task in the background (even if the browser is closed) without waiting for a response on a button click event of a web page. 我必须启动一个线程来在后台执行一些长时间运行的任务(即使关闭了浏览器),而不必等待网页的按钮单击事件的响应。

I also need to be able to stop that later if the user wishes to do so. 如果用户希望这样做,我也需要稍后再停止。

How can I do this? 我怎样才能做到这一点?

Is it possible to store the id of the thread in database and abort it later? 是否可以在数据库中存储线程的id并在以后中止?

Do I need to make an asynchronous webservice OR wcf call to achieve this? 我是否需要进行异步webservicewcf调用来实现此目的?

How can I stop the long running task later if required in that case? 在这种情况下,如果以后需要如何停止长时间运行的任务?

Thanks in advance. 提前致谢。

I suggest that your ASP.Net app write requests to a database table, and handle those requests with a Windows service. 我建议您的ASP.Net应用程序将请求写入数据库表,并使用Windows服务处理这些请求。

I would use one table to queue new tasks and a separate table to manage running tasks. 我将使用一个表对新任务进行排队,并使用一个单独的表来管理正在运行的任务。 This second table can be used to report progress or kill a running task. 第二个表可用于报告进度或终止正在运行的任务。 Once tasks complete you can move them to a third table long with summary data for later analysis. 任务完成后,您可以将它们移动到包含摘要数据的第三表中,以供以后分析。

The database also gives you persistence, so if the server crashes the Windows service can provide automatic restart of the tasks without requiring the user to resubmit them. 数据库还为您提供了持久性,因此,如果服务器崩溃,Windows服务可以自动重启任务,而无需用户重新提交它们。

If you have lots of queued tasks, you can spawn Windows services on multiple application servers to speed things up, all controlled through the database. 如果您有许多排队的任务,则可以在多个应用程序服务器上生成Windows服务以加快处理速度,所有这些操作都通过数据库进行控制。

You can use the backgroundworker class: 您可以使用backgroundworker类:

Instantiate a backgroundworker, define a DoWork event handler and a RunWorkerCompleted event handler. 实例化后台工作程序,定义DoWork事件处理程序和RunWorkerCompleted事件处理程序。 Then start the action using the RunWorkerAsync method. 然后使用RunWorkerAsync方法开始操作。 You can cancel the action using the CancelAsync method. 您可以使用CancelAsync方法取消操作。

Maybe you can store a reference to your worker in cache or in application (or in Session if it is user specific) to retrieve it when you need to cancel. 也许您可以将对您的工作程序的引用存储在缓存中或应用程序中(如果是特定于用户的,则可以存储在Session中)以在需要取消时检索它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM