views:

32

answers:

2

Hi, 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 and be able to stop that later if 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.

A: 

Hi,

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.

GôTô
+1  A: 

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.

ebpower
that's what I almost decided, because of various issues involved (like load balancers etc) in managing long running tasks on the webserver. windows service can start multiple threads to perform the tasks in parallel. the only issue with windows service is that it needs to keep polling the database every second or few mins to check for new requests, which is not efficient in off-peak time, it will be better if it is somehow event driven, like an event is published when user makes a request and a service subscribes to it and acts ONLY when there is a new request. do I need to use MSMQ for this?
RKP
You could try MSMQEvent and see if it works for you. Polling shouldn't put much of a load on the server unless you're constantly hammering it. You can back off on the interval during off-peak hours if that's a big deal. But the purpose of the machines is to do things, so if its not doing anything else what wrong with some polling?
ebpower
thanks for the reply
RKP