[RESOLVED]Response waits for BackgroundWorker

I have modified the sample HomeController to illustrate I problem that I have in my real application.  In my real application I want a user to not wait for a longer running background process.  I found that the response is not being returned to the user
until the background process has finished which defeats the purpose of having a background task.  Here is my modified sample MVC 2 application to illustrate.

[HandleError]
public class HomeController : Controller
{
    static System.ComponentModel.BackgroundWorker bw;


    static HomeController()
    {
        bw = new System.ComponentModel.BackgroundWorker();
        bw.DoWork += bw_DoWork;
    }


    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";


        return View();
    }


    public ActionResult About()
    {
        bw.RunWorkerAsync();
        return View();
    }


    static void bw_DoWork(object sender,
                                    System.ComponentModel.DoWorkEventArgs e)
    {
        System.Threading.Thread.Sleep(20000);
    }
}

When I click on About from the home page it takes ~20 seconds for the About page to appear.  If I remove the Sleep(20000) from the background task then the page appears instantly.  I expect a BackgroundWorker task to run in the background!  What am I doing
wrong?

I’ve abandoned BackgroundWorkerItem changed to using ThreadPool.QueueUserWorkItem() and everything works fine now. 

You can also use Ajax Request, which will also notify you when long request completes. You can find some idea

here

Paul Linton

I’ve abandoned BackgroundWorkerItem changed to using ThreadPool.QueueUserWorkItem() and everything works fine now. 

I have seen BackgroundWorker more in Desktop Application. I think that the problem relates to  HostProtectionAttribute :

"The
HostProtectionAttribute
attribute applied to this type or member has the following

Resources
property value: SharedState. The
HostProtectionAttribute
does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the

HostProtectionAttribute
class or
SQL Server Programming and Host Protection Attributes
."

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Leave a Reply