Do Not .Dispose In The PreRender Event
Posted by Davy Brion on October 1st, 2008
We had this weird issue with a project at work… sometimes, the web application would just completely hang for a couple of minutes. A coworker started looking at the problem, and he quickly found out that in some cases, calls to the WCF service would just completely block. Even when debugging the web application and the WCF service on our development machines, so it wasn’t an issue of throughput or concurrency or anything like that on the server.
We were clueless as to why the calls were actually blocking. We had a few scenarios that would usually (but not always) trigger the bug, but it also occurred in other situations, seemingly at random. So my coworker spent many hours trying to find out why it was happening. After a lot of debugging on his part, he found out that sometimes our WCF proxies weren’t being disposed, which left Channels to the service open which caused new proxies to block whenever the number of allowed concurrent channels was reached. My first reaction was “huh, how could that be? i’m disposing of them in the page’s PreRender event…”.
First of all, i’m far from an ASP.NET guru, so those of you who do know a lot about it probably already understand the problem. I figured that the PreRender event would always occur, and that it would be the best place to dispose the WCF proxy. That turned out to be a two-for-one brain fart on my part. First of all, the PreRender event is obviously not fired when you do a Server.Redirect or Server.Transfer, so whenever we navigated to another page, we did not dispose our WCF proxy. Secondly, Page inherits IDisposable, which i completely missed apparently. So, had i simply overridden the Dispose method and dispose the proxy in there before calling base.Dispose() and then we would’ve never had this problem to begin with.
Lesson of the day: no matter how careful you try to be, you can still fuck up pretty bad sometimes
Update: i actually used the PreRenderComplete event instead of the PreRender event… still, a bad place to dispose of disposable objects
October 2nd, 2008 at 11:59 pm
According to my experiences, if you get a random erroneous behavior which you can not reproduce easily, most of the time this behavior stems from a memory related issue.