6

We have a very tricky interop problem wherein the thread used to initialize a 3rd-party system has to be the same thread used to terminate it. Failure to do this results in a deadlock. We are performing interop from a WCF service hosted in IIS. Currently this cleanup is done in disposal and normally works very well. Unfortunately, under heavy load IIS will do a rude unload and we never get to call dispose. We can move the shutdown logic into a critical finalizer but that doesn't help since we no longer have access to the initializing thread! At this point our only recourse seems to be notifying the CLR that the AppDomain is now likely in a corrupted state. However, I'm not sure how to do that (or if it's even possible). It may be that this is the utility of contracts at a class level but I admit I don't really understand those fully.

EDIT: Alternatively, this is could be viewed as a thread affinity problem in the finalizer. If anyone has a clever solution to that, I'm all ears :)

Jeff
  • 2,701
  • 2
  • 22
  • 35

1 Answers1

1

Try to split the code that depends on that native dependency to a standalone Windows service application if possible. If it cannot work well with WCF/IIS, you should avoid the conflicts instead of fighting against it.

Lex Li
  • 60,503
  • 9
  • 116
  • 147
  • Yes, you may be right. We've talked about this although I'm reluctant to give in just yet :) – Jeff Mar 13 '12 at 14:00
  • Also, I should have said - I'm not sure this actually solves the problem since CLR unloads are probably a fact of life (although less likely in your solution, I'm sure). – Jeff Mar 13 '12 at 14:37
  • Do you mean that you feel bad about the application unload? It is by design, as the application pool will be recycled periodically (learn the settings), and ASP.NET also restarts, http://stackoverflow.com/questions/829392/how-to-discover-the-reason-of-asp-net-application-restart – Lex Li Mar 14 '12 at 09:34
  • I'm not sure what you mean by "feel bad". When the application unloads my "finally" blocks don't get called. This is a CLR behavior, not really an ASP.NET behavior although - as I said - it's more likely to manifest in IIS. – Jeff Mar 21 '12 at 15:54
  • Well, all .NET developers have to adapt to the facts that finalizers are not ensured to be called. Therefore, it is not easy to resolve the interop problem you meet solely in ASP.NET. In ASP.NET model, there is no way to control the lifecycle of the objects as that's managed by ASP.NET/IIS. However, moving the piece to a Windows service application should give you more control on the object lifecycle. – Lex Li Mar 26 '12 at 07:52
  • Again, I think you're confusing ASP.NET and the CLR. ASP.NET does not control the lifetime of objects (although it may control the lifetime of an app domain), the CLR does. The idea of constrained execution (or a critical finalizer) is well established in the CLR. – Jeff Apr 02 '12 at 22:32