I got an windows service application which dynamically loads some other modules in other new appdomain. The problem is they are all using the same static database connections. I can dispose the static connections in the main AppDomain when I shutdown the service. But how can I immediately dispose the other static connections in other AppDomain. The problem is since the other connections still exist, the service application still runs in the Task Manager even I fully stop it.
Thanks
The problem is they are all using the same static database connections.
Yes, that is definitely a problem. Don't do that. Connections are pooled by .NET and are not expensive to create, so the proper pattern is to create them when you need them, use them, and dispose of them when you're done. An effective way of doing that is with using statements.
in general, whatever creates a disposable object is responsible for disposing of it. since your disposable objects are static, there is no way to know what is responsible for disposing of it. So you need to have logic to see if it's already been disposed, if it's open, if it's null, etc. It's much cleaner to just keep all of the creation and disposal logic in one place.
Related
My windows service is using .Net managed objects like Sockets, Threads, Monitors, Semaphores. I have two questions related to these objects.
Do we have to implement IDisposable.Dispose on classes using above managed objects, to release them in order to assist when the service stops.
We also have threads waiting on monitors. If we don't stop/exit them before exiting does the Garbage collector clean them?
When you use IDisposables, you should dispose them somewhere. If they are references in fields, you usually need to implement IDisposable in that class and dispose it there. Threads should be stopped (using e.g. a reset event) and joined.
I am dealing with some legacy code that probably predates .NET 2. The library itself is custom asynchronous TCP communication layer used by our server.
There is a class there inheriting from System.Net.Sockets.TcpClient and the whole class hierarchy around it that implements dispose pattern and finalizers (the latter likely not needed).
My question is about suspicious line of code found in the method that handle TCP client disconnected event:
// Hack to ensure that client has disconnected
GC.Collect();
which is executed after calling methods disposing of our communication class hierarchy that eventually calls System.Net.Sockets.TcpClient Dispose method.
On a 64-bit server that can serve many clients and use gigabytes of RAM these calls can be quite expensive. I could not find anything about forcing garbage collection upon TCP client disconnection?
Two things will happen after you force GC with GC.Collect().
Memory used by unreachable objects that don't have finalizers will be reclaimed.
Objects that implement finalizers will be placed on finalizer queue, and the finalizers will be executed soon.
The comment suggests that GC.Collect() is not called to reclaim memory, but rather to execute finalizers to dispose unmanaged resources.
If IDisposable is used correctly, there is no need to rely on finalizers. Probably there are some IDisposable objects that are not Disposed correctly. You'll have to find them. One way to do it is to examine what finalizers are executed. Some memory profilers can also track such objects (for example .NET memory profiler's Dispose Tracker).
Objects like FileStream, CryptoStream etc ...
Or I must manually dispose them.
I'm using Thread.IsBackground = true to terminate my working thread when user clicks on form close button.
Let's break that down into multiple questions:
Will operating system resources such as file handles be automatically closed when my program terminates?
Generally speaking, yes. The operating system will automatically close all resources associated with the process when the process is destroyed.
Suppose I have non-operating-system resources, like database connections. Will my application automatically send a message to the database saying that the connection is closed?
Not necessarily. However, the database should be written to be robust in the face of a flaky client.
Should I clean up my resources even though I don't need to?
In a "normal" shutdown, yes. Suppose you have a resource leak in the future. It is going to be a lot easier to find the leak if you've had good discipline and always release your resources when you're done with them. Shut down your program in an orderly fashion.
In an "emergency" shutdown, just shut down as soon as possible. If the program is going down because of some fatal error, trying to clean up might just make it worse. Don't spend time sweeping the floors before the building collapses.
Whether all objects [...] be automatically disposed when program terminates?
Yes. Ultimately all unmanaged resources are allocate from the OS (Windows) and when a process terminates, all its resources are freed. But that does not mean that all your Dispose() methods will be called, you have no guarantees on them. So don't put anything vital there.
All object will automatically be disposed if not disposed manually....at an indeterminate time in the future.
Assuming they are built correctly.
There are instances where the finalizers will not be run, for example if an exception is thrown from a finalizer, or if something calls Environment.FailFast().
So it's certainly not something you can rely on.
You might also want to add this to the end of your Main() method:
GC.Collect();
GC.WaitForPendingFinalizers();
However, I think that any code that relies on this is broken.
How much work should be done in a Dispose method? In constructors I've always taken the stance that you should only do what is absolutely necessary to instantiate the object. This being the case I've also always taken the approach that you should ONLY be cleaning up open resources when disposing. Closing files, freeing memory, disposing of child disposable object, etc. You shouldn't be doing lengthy processes like touching files, accessing databases and such in the Dispose method.
Am I wrong? Are those action's OK as long as you are handling any possible exceptions so they don't bubble out of the method? I just don't think doing a lot in Dispose is a good idea. I would like to know what the community thinks.
Am I wrong?
No, you are right. In general the Dispose method is used to clean the unmanaged resources that your class might have allocated.
But that's difficult to generalize. There are cases where the Dispose method is simply used to ensure that some operation executes. For example in ASP.NET MVC there's the Html.BeginForm helper which is used like that:
using (Html.BeginForm())
{
}
and all that the Dispose method does is render a closing </form> tag. So as you can see people could be creative with the pattern and it is very difficult to draw conclusions without a specific scenario.
But in the most common situations it's used to release unmanaged resources.
"It depends". What kind of database/file access are we talking about? Say for example that your disposable object is some sort of logger and you use it in the following pattern
using(Logger logger = new Logger())
{
foo.PerformTask();
}
I think it would be perfectly acceptable for logger to write out "Log started" in the constructor "Log Completed" in Dispose.
How much work should be done in a Dispose method?
This depends, are you implementing the IDispose interface just for the convenience of a 'using' statement, or are you implementing the full IDisposable pattern? In the later case of a full disposable pattern it is still acceptable to perform more complex actions provided that you're 'disposing' parameter is true (i.e. you are not in GC).
When you are defining a finalizer that calls the Dispose method there really is not too much to be concerned about. Similar uses/abuses of the IDisposable interface mentioned already be others (i.e. using (Html.BeginForm())) are capable of performing any action. Often this can greatly reduce code complexity and prevent coders from accidentally forgetting to perform some closing action. One down (or up) side to this is that code executes a little differently inside a finally block.
In constructors I've always taken the stance that you should only do what is absolutely necessary to instantiate the object.
Objects, IMHO, should be valid post construction. So if you have a lot of work to do to construct something so be it. Don't think of the workload involved, think of the consumer of you're object and it's usability. Post-construction Initialize() methods suck ;)
This being the case I've also always taken the approach that you should ONLY be cleaning up open resources when disposing. Closing files, freeing memory, disposing of child disposable object, etc. You shouldn't be doing lengthy processes like touching files, accessing databases and such in the Dispose method.
Actually let's break this down a bit...
Disposing from the GC call to the Finalizer
When you implement the IDisposable pattern (not the interface, the pattern, finalizer and all) you are essentially saying that your object has an unmanaged resource that nobody else knows about. That means you have PInvoked a call to Win32's CreateFile, or maybe you called Marshal.AllocHGlobal or something like that. Essentially you likely have an IntPtr instance member you need to do something with to prevent a memory leak. These are the ONLY types of things that should be done when the disposing parameter is false (i.e. called from the finalizer on the GC thread).
Generally you DO NOT call the Dispose method on children. You should not expect any child object to be valid. Simply touching a member of the child object can accidentally 'revive' or resurrect it.
So when you are writing code that executes in a Dispose method called from the Finalizer you have to be careful. You are executing on the GC thread while the rest of your application waits for you. You should perform as few operations as possible to release the unmanaged memory/resource and quit. Never throw an exception and if you are calling an API that may throw you should catch any exception raised. Propagating exceptions back to the GC will prematurely abort the finalizer thread and the remaining objects to be finalized will not have a chance to clean up.
Disposing from the IDisposable.Dispose() method
As I’ve already said, using the Dispose method is safe enough and can safely accommodate any amount of code/process. This is where you would free unmanaged resources, call the dispose method of child objects, flush and close files, etc. Most of the Dispose methods I’ve written do not have an associated Finalizer and therefore do not follow the IDisposable pattern, yet they implement IDisposable just for the convenience of the using statement.
Am I wrong? Are those action's OK as long as you are handling any possible exceptions so they don't bubble out of the method? I just don't think doing a lot in Dispose is a good idea. I would like to know what the community thinks.
You are absolutely right when the dispose method in question is used from a finalizer. You’re assertions about what you should and should not do in a Dispose method should actually be reworded to apply to anything called by a Finalizer. The fact that this is generally done in a method called Dispose is a matter of convention, the IDisposable pattern, but these issues could easily exist in other methods used by the Finalizer.
If an object does something to the state of some outside entities in a way which makes them more useful to that but less useful to everyone else, the Dispose method of the object should do whatever is necessary to restore outside those entities to more generally-useful state. If one wishes to avoid having an object do too much work in Dispose, one should design the object so as never leave any outside entities in a state which would be onerous to clean up.
BTW, Microsoft likes to use the term "unmanaged resources", and gives examples, but never really offers a good definition. I would suggest that an object holds an "unmanaged resource" if an outside entity is altering its behavior on behalf of that object, in a fashion which is detrimental to other objects or entities, and if that outside entity will continue to alter its behavior until the object stops it from doing so.
You should lean toward the conclusion you have already come to. However there are situations where you need to ensure that services are stopped and that could include things like messages being logged for the service shutdown, or saving the current runtime state to data store. This type of disposal usually only applies to things that have a lifestyle that is application scope, meaning they exist the whole time the application is running. So there are situations outside of the expected norm. As is the case with every rule you should follow when writing code.
Does the garbage collector clean up web service references or do I need to call dispose on the service reference after I'm finished calling whatever method I call?
Instead of worrying about disposing your web services, you could keep only a single instance of each web service, using a singleton pattern. Web services are stateless, so they can safely be shared between connections and threads on a web server.
Here is an example of a Web Service class you can use to hold references to your web service instances. This singleton is lazy and thread-safe. It is advised that if you make your singletons lazy, they are also kept thread safe by following the same logic. To learn more about how to do this, read the C# In Depth article on Implementing Singletons.
Also keep in mind that you may run into issues with WCF web services. I'd recommend reading up on WCF's instance management techniques article, specifically the singleton section, for more details.
public static class WS
{
private static object sync = new object();
private static MyWebService _MyWebServiceInstance;
public static MyWebService MyWebServiceInstance
{
get
{
if (_MyWebServiceInstance == null)
{
lock (sync)
{
if (_MyWebServiceInstance == null)
{
_MyWebServiceInstance= new MyWebService();
}
}
}
return _MyWebServiceInstance;
}
}
}
And then when you need to access your web service, you can do this:
WS.MyWebServiceInstance.MyMethod(...)
or
var ws = WS.MyWebServiceInstance;
ws.MyMethod(...)
I've successfully used this pattern on several projects and it has worked well, but as tvanfosson mentions in the comments below, an even better strategy would be to use a DI framework to manage your web service instances.
I think the DataService inherits Dispose from Component.
Objects that implement IDispose should be disposed of manually to assist the garbage collector.
If you object is short lived use a using block. For objects that can be retained ensure that they object that retains them disposes of them when it is also disposed.
what are you trying to accomplish here?
If your worried about performance, then I would worry more about the responsiveness of the server hosting the webservice and the network speed, as they can dramatically affect the length of time you have to wait for the webservice call to complete (unless its asynchronous).
The examples on MSDN dont call 'Dispose' and its quite obvious that the garbage collector will do its job, so unless your working on a realtime system that needs to process over 100,000 records in memory every second, then maybe you dont need to come up with a way to dispose resources or manage memory.
I think the concerns of Seabizkit in the above answer are very legitimate.
It's quoted here:
#DanHerbert what happens when two threads call the singleton.. let me explain... there is a lock on the object.. to make it thread safe. Does that mean that if theard1 call accesses webInstance, then thread2 will wait on thread1 to finish. or is the lock purely for the creatation of the instance. say you have 10 callers.... does the lock mean they are chained... or async, i think you will get what I'm asking let me know if it wasn't clear. – Seabizkit Oct 13 '16 at 10:01
<
After I've done some testing I can tell that you won't be able to get any good performance when a single 'client' object is used by multiple different threads.
If ten threads are created and they all are using the same singleton 'client' then they will have to wait in line until all previous calls are done.
To see the proof for that please read and run a sample in this c-sharp corner article here:
https://www.c-sharpcorner.com/article/increase-performance-with-an-object-pool-or-why-singleton-may-cause-performance/
titled "Increase Performance with an Object Pool or Why Singleton May Cause Performance Issues".
Sorry to burst the bubble of the singleton web service users. Also, you would be very hard-pressed to find Microsoft's example where the web service client is "caged" in the singleton.