Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm going through a big refactoring / speed tweaking of one of my larger MVC apps. It has been deployed to production for a few months now, and I was starting to get timeouts waiting for connections in the connection pool. I have tracked the issue down to the connections not getting disposed properly.

In light of that, I have since made this change to my base controller:

public class MyBaseController : Controller
{
    private ConfigurationManager configManager;  // Manages the data context.

    public MyBaseController()
    {
         configManager = new ConfigurationManager();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (this.configManager != null)
            {
                this.configManager.Dispose();
                this.configManager = null;
            }
        }

        base.Dispose(disposing);
    }
}

Now, I have two questions:

  1. Am I introducing a race condition? Since the configManager manages the DataContext that exposes IQueryable<> parameters to the views, I need to make sure that Dispose() will not be called on the controller before the view finishes rendering.
  2. Does the MVC framework call Dispose() on the Controller before or after the view is rendered? Or, does the MVC framework leave that up to the GarbageCollector?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
609 views
Welcome To Ask or Share your Answers For Others

1 Answer

Dispose is called after the view is rendered, always.

The view is rendered in the call to ActionResult.ExecuteResult. That's called (indirectly) by ControllerActionInvoker.InvokeAction, which is in turn called by ControllerBase.ExecuteCore.

Since the controller is in the call stack when the view is rendered, it cannot be disposed then.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...