Should a managed class that wraps a DirectSound interface be IDisposable? - c++-cli

I'm writing a managed wrapper around DirectSound. (It's a simple partial wrapper that solves my specific problem and nothing more. Don't tell me about NAudio or whatever.) Should a managed class that wraps IDirectSound8 be IDisposable and why? Same question about IDirectSoundBuffer8.

Technically: yes. Practically: no. IDirectSound8 is a COM interface, they are very conveniently wrapped in .NET with a interop library. An RCW. That RCW manages the reference counts on the underlying COM coclass object. An RCW does not implement IDisposable, even though it very much hangs on to an unmanaged resource.
The reason it doesn't is because it is almost impossible to implement IDisposable correctly. A COM coclass implements multiple interfaces, creating one adds to the reference count. You would have to be 100% sure that all of those interface pointers are no longer in use before a dispose would be safe. That's very hard to do, those pointers get created in unexpected ways. Like using an indexed property of one of the interfaces, the intermediate interface pointer is never visible in your code.
This is not a real problem, the garbage collector takes care of the reference counts, the finalizer gets the job done. It is just that it takes a bit longer for the object to be released. Standard GC behavior. Unfortunately out-of-process COM servers have observable side-effects, programmers tend to get annoyed when the process doesn't disappear from the TaskMgr processes list at the instant their code stops using the interfaces. Many, many "Excel/Word doesn't quit" questions here and at the forums.
If you want to implement it anyway then you can do so by calling Marshal.FinalReleaseComObject() in your Dispose() implementation. Just beware of the significantly increased risk for failure, getting that call wrong produces very hard to diagnose failure. Not quite unlike deleting an object in native code and still having a pointer to it. If it is actually a "heavy" object that must be released instantly then GC.Collect() + GC.WaitForPendingFinalizers() gets the job done too with much less risk of getting it wrong. With side-effects of course.

Related

Benefit to clearing DataTables

I'm wondering if there is a benefit to clearing data tables of information once you are done, is there a noticeable problem if I don't clean the tables out. I know the process of clearing the table out is only one line, but I"m wondering the benefits it's providing, and if the tables will automatically be cleared when I exit a run of the application or will they remain until a computer is restarted?
Example:
Me.dtSet.Tables("ExampleTable").Clear()
Please, see this thread
It essentially states that there is no benefit to disposing of a DataSet / DataTable.
Also:
DataSet and DataTable don't actually have any unmanaged resources, so Dispose() doesn't actually do much. The Dispose() methods in DataSet and DataTable exists ONLY because of side effect of inheritance - in other words, it doesn't actually do anything useful in the finalization.
It turns out that DataSets, DataViews, DataTables suppress finalization in their constructorsc this is why calling Dispose() on them explicitly does nothing.
Presumably, this happens because, as mentioned above, they don’t have unmanaged resources; so despite the fact that MarshalByValueComponent makes allowances for unmanaged resources, these particular implementations don’t have the need and can therefore forgo finalization.
Overview of this Immense Answer:
Without a doubt, Dispose should be called on any Finalizable objects.
DataTables are Finalizable.
Calling Dispose significantly speeds up the reclaiming of memory.
MarshalByValueComponent calls GC.SuppressFinalize(this) in its Dispose() - skipping this means having to wait for dozens if not hundreds of Gen0 collections before memory is reclaimed.
From here, By: Killercam
If those don't fully answer your question, perhaps read this answer.
An important takeaway to your question ->
"Does Dispose() method does not free up the memory & make object as null ??
Dispose and the disposal pattern is not for reclaiming managed memory or "deleting" managed objects (both things you cannot do and what the Garbage Collector is there for), it is for handling the disposal/release of unmanaged resources or other managed resources that have releasable items, such as SqlConnection. It certainly won't null the reference, but may make it unusable from the time of disposal forwards."

Are there any alternative concepts for handling unmanaged resources in garbage collected languages?

Garbage collected object oriented programming languages reclaim unused memory automatically, but all other kinds of resources (i.e. files, sockets...) still require manual release since finalizers cannot be trusted to run in time (or at all).
Therefore such resource objects usually provide some kind of "close"- or "dispose"-method/pattern, which can be problematic for a number of reasons:
Dispose has to be called manually which may pose problems in cases when it is not clear when the resource has to be released (similar problem as with manual memory management)
The disposable-pattern is somewhat "viral", since each class containing a disposable resource must be made disposable as well in order to guarantee correct resource cleanup
An addition of a disposable member to a class, requiring the class to become disposable as well, changes the interface and the usage patterns of the class, thus breaking encapsulation
The disposable-pattern creates problems with inheritance, i.e. when a derived class is disposable, while the base class isn't
So, are there any alternative concepts/approaches for properly releasing such resources? Any papers/research in that direction?
One approach (in languages that support it) is to manually trigger a garbage collection event to cause finalizers to run. However, some languages (like Java) do not provide a reliable mechanism for doing so.

When a form disposed, are all form data and datasets also disposed?

As the title, When a form disposed, are all form data and datasets also disposed?
Example:
Dim C As New Commands
C.ShowDialog
C.Disopse()
So C form contains datasets and oledbconnections and more objects that were not disposed . If not, what is the best method to free memory and release all resources?
As with other .NET objects, you cannot guarantee datasets will be disposed when the form is disposed. This is because .NET constantly monitors whether or not there are active pointers to the objects in memory. If no links were found, it frees up memory allocated to the object. Such process is called garbage collection - a feature of CLR.
Problem is that you can have a variable that points to the same data set, on another form, class, and even in another project. You can spawn as many of those variables as you want. As a developer, you must work out a strategy to control who consumes your objects and how. Otherwise you will never know if at any given moment a particular dataset was actually disposed.
Using clause helps control disposal of objects, but it's not the ultimate solution. You can still get in trouble if you don't know what you are doing. And sometimes you would need to pass undisposed connection objects to other functions on purpose, for more granular control over data processing.
A form's .Dispose() method is there to handle the otherwise-unmanaged GDI resources used by the form. Since that method doesn't know anything else about what you might have added, you can't be sure that items such as datasets are disposed as well.
The best you can hope for is that since Dispose()-ing a form is also highly indicative that the form is about to become eligible for garbage collection, your other resources are also likely about to become eligible for garbage collection. If the Dispose() and finalizer patterns for those types was implemented correctly, then it is highly likely that your other items will be disposed soon. Just how soon is impossible to say... that's why the dispose pattern exists: for those times when you need to sure an unmanaged resource is cleaned up right away.
The way I would recommend freeing any additional resources is to override the normal Windows Forms Dispose() method. Your new implementation of the Dispose() method will call the base implementation using the MyBase keyword, and also call Dispose() for any IDisposable members of your form. This way, the form will still work correctly as part of a Using block.

Avoid COM marshalling

I'm a little confused about com threading models.
I have an inproc server and I want to create an interface accesible from any thread regardless of the threading-model and/or flags used in CoInitializeEx.
When passing interfaces from one thread to another I use CoMarshalInterface/CoUnmarshalInterface without problems but I want to know if exists any way to avoid that and directly pass the interface pointer.
I tried making the interface use neutral apartment but still have to call CoMarshalInterface/CoUnmarshalInterface to avoid problems.
Regards,
Mauro.
COM objects reside in one apartment only. Accessing a COM object via an interface pointer across apartment boundaries is never a good idea unless you're applicable scenario can utilize a free threaded marshaling aggregate. A free-threaded marshaller, essentially says that all clients of this interface, regardless of apartment and thread, are in the same process and will rely on the object itself to maintain synchronization and thread safety. The object itself must aggregate the free-threaded marshaller interface, so hopefully you're the author of it as well as the client code.
More information on free-threaded marshaling can be found at msdn.com, but one of their articles covering the object I tend to reuse again and again is this one.
I hope it helps you out.

Should all classes implement the IDisposable interface?

(very newbie questions)
i may be misunderstanding this but on MSDN i believe it says that it is good practice to implement the Dispose destructor in every class you write. should i (do you) really implement the IDisposable interface with every class i write?
also, is the proper syntax for implementing an interface to put the "Implements" keyword on the line after the "class" declaration? i put it on the same line as "class" and I got an error.
one more?: when coding the method implemented by the interface, is it mandatory to follow this syntax, as an example:
Public Sub Dispose() Implements IDisposable.Dispose
what i'm curious about in the above code, is if i need to declare the implemented method as
"Implements System.IDisposable.Dispose"
You should only implement IDisposable if your class holds instances of other classes that implement IDisposable, or if it holds native resources.
For more information, see this article.
No you should not. Only implement IDisposable if you are using unmanaged resources directly or have members that implement IDisposable and want to make sure their dispose method gets called when the dispose method gets called on your class.
Many actions a computer might perform create the need for a counter-balancing "cleanup" action. For example, the act of opening a file creates a need to close it. The act of placing a call with a modem creates the need to disconnect it. Performing an action without performing the required counter-balancing cleanup may sometimes be harmless, but may sometimes have severe consequences in the computer or in the real world (failing to close a file before a user ejects the media may cause file corruption and data loss; failing to terminate a modem connection may cost someone many dollars in excess phone charges).
The purpose of IDisposable is provide a means by which well-behaved programs can make sure that any cleanup actions that need to be performed actually get done. Any routine which performs an operation that must be counter-balanced by cleanup should keep the information and impetus necessary to perform such cleanup until such time as it has been performed; if the routine can't perform such cleanup before returning to the caller, it should either (1) provide the information to the caller, and be documented as requiring the caller to use that information to perform the cleanup, or (2) keep the necessary information in one or more fields, and implement IDisposable; when IDisposable.Dispose is called, the object should use the saved information to perform the cleanup.
Note that IDisposable only works cleanly if any object that requests the creation of an IDisposable object accepts and honors the responsibility of making sure that the object's IDisposable.Dispose method will be called sometime. The system does provide a "backup" means, called finalization, which objects can use to ensure that they get a chance to perform their cleanup. Essentially, an object registers a request with the system that says "Let me know if I've been abandoned". If the system detects that an object has been abandoned, it will try to give the object a chance to perform any necessary cleanup. Note the system may take awhile to notice that an object has been abandoned, and for various reasons the notifications may not always happen. It is almost always much better to call IDisposable.Dispose on objects before they are abandoned, than to rely upon the "last chance" finalization mechanism.
The .Net framework has a garbage collector and for the most part manages allocation and release of memory for you (when creating a new object). However you also need to manage un-managed resources (I also seen being refereed to as native resources). So now the garbage collector is not good enough and you have to manage memory using the IDisposable interface. A good example is creating the DataAccesslayer where you handle database connection and use the IDisposable interface
check this out to see how to implement iDisposable interface:
https://msdn.microsoft.com/en-us/library/498928w2%28v=vs.110%29.aspx