views:

252

answers:

2

I have a task that is not important ; it should be run once in while if the website is used.

So I tried this approach : http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

The task could be long so I want it to be asynchronous... so that the navigation is not stopped by the background task.

The thing I don't understand is that when I start debugging (attach to process w3wp.exe) I can't navigate on the site anymore until I stop debugging?

Here is the code (ResourceService being a WCF service hosted on ISS in the same project) :

private void CacheItemRemoved(string taskName, object seconds, CacheItemRemovedReason r)
    {
        switch (taskName)
        {
            case MedianamikTasks.UpdateResources:
                if (Config.EnableAutoResourceUpdate)
                {
                    ThreadStart threadStart = ResourceService.UpdateResources;
                    var thread = new Thread(threadStart) {IsBackground = true};
                    thread.Start();

                    //Do not use... : http://csharpfeeds.com/post/5415/Dont_use_the_ThreadPool_in_ASP.NET.aspx
                    //ThreadPool.QueueUserWorkItem(x => ResourceService.UpdateResources());
                }
                break;
        }

        AddTask(taskName, Convert.ToInt32(seconds));
    }
A: 

Use a background worker.

BackgroundWorker worker;  
worker = new BackgroundWorker();  
worker.DoWork += new DoWorkEventHandler(worker_DoWork);  
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);  
worker.RunWorkerAsync();

Then in the DoWork handler call the method that you need

Kevin
+1  A: 

The thing I don't understand is that when I start debugging (attach to process w3wp.exe) I can't navigate on the site anymore until I stop debugging?

Just a guess, but do you have a breakpoint set? As soon as you hit a breakpoint the execution in the w3wp processes will stop at that point, thus you won't be able to 'navigate' around the site.

Brendan Kowitz
If I understand : the threads are contained in the (w3wp) process (processes?) so that even if the task is started in another thread and asynchronous, stopping on breakpoint (inside the asynchronous task) while debugging will always block all the threads of the process (therefore I can't navigate anymore)?
W3Max
While you are Debugging, you can view the menu item in VS: Debug|Windows|Threads to see and switch between all threads owned by that process. And yes, they will all be paused. Hope that helps you out.
Brendan Kowitz