开发者

starting and stopping threads from ASP.NET

开发者 https://www.devze.com 2023-01-19 19:52 出处:网络
I have to start a thread to do some long running task in the ba开发者_开发问答ckground (even if the browser is closed) without waiting for a response on a button click event of a web page.

I have to start a thread to do some long running task in the ba开发者_开发问答ckground (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?

Do I need to make an asynchronous webservice OR wcf call to achieve this?

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.

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.

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.


You can use the backgroundworker class:

Instantiate a backgroundworker, define a DoWork event handler and a RunWorkerCompleted event handler. Then start the action using the RunWorkerAsync method. You can cancel the action using the CancelAsync method.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消