Search Results

Search found 257 results on 11 pages for 'idisposable'.

Page 1/11 | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Implementing IDisposable on a subclass when the parent also implements IDisposable

    - by Tanzelax
    I have a parent and child class that both need to implement IDisposable. Where should virtual (and base.Dispose()?) calls come into play? When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else. What I had been doing (trivialized quite a bit): internal class FooBase : IDisposable { Socket baseSocket; private void SendNormalShutdown() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool _disposed = false; protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { SendNormalShutdown(); } baseSocket.Close(); } } ~FooBase() { Dispose(false); } } internal class Foo : FooBase, IDisposable { Socket extraSocket; private bool _disposed = false; protected override void Dispose(bool disposing) { if (!_disposed) { extraSocket.Close(); } base.Dispose(disposing); } ~Foo() { Dispose(false); } }

    Read the article

  • How to find all Classes implemeting IDisposable?

    - by apoorv020
    I am working on a large project, and one of my tasks is to remove possible memory leaks. In my code, I have noticed several IDisposable items not being disposed of, and have fixed that. However, that leads me to a more basic question, how do I find all classes used in my project that implement IDisposable? (Not custom created classes by normal Library classes). I have already found one less-than-obvious class that implements IDisposable ( DataTable implements MarshalByValueComponent, which inherits IDisposable). Right now, I am manually checking any suspected classes by using MSDN, but isn't there some way through which I can automate this process?

    Read the article

  • How do you prevent IDisposable from spreading to all your classes?

    - by GrahamS
    Start with these simple classes... Let's say I have a simple set of classes like this: class Bus { Driver busDriver = new Driver(); } class Driver { Shoe[] shoes = { new Shoe(), new Shoe() }; } class Shoe { Shoelace lace = new Shoelace(); } class Shoelace { bool tied = false; } A Bus has a Driver, the Driver has two Shoes, each Shoe has a Shoelace. All very silly. Add an IDisposable object to Shoelace Later I decide that some operation on the Shoelace could be multi-threaded, so I add an EventWaitHandle for the threads to communicate with. So Shoelace now looks like this: class Shoelace { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; // ... other stuff .. } Implement IDisposable on Shoelace Buit now FxCop will complain: "Implement IDisposable on 'Shoelace' because it creates members of the following IDisposable types: 'EventWaitHandle'." Okay, I implement IDisposable on Shoelace and my neat little class becomes this horrible mess: class Shoelace : IDisposable { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Shoelace() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (waitHandle != null) { waitHandle.Close(); waitHandle = null; } } // No unmanaged resources to release otherwise they'd go here. } disposed = true; } } Or (as pointed out by commenters) since Shoelace itself has no unmanaged resources, I might use the simpler dispose implementation without needing the Dispose(bool) and Destructor: class Shoelace : IDisposable { private AutoResetEvent waitHandle = new AutoResetEvent(false); bool tied = false; public void Dispose() { if (waitHandle != null) { waitHandle.Close(); waitHandle = null; } GC.SuppressFinalize(this); } } Watch in horror as IDisposable spreads Right that's that fixed. But now FxCop will complain that Shoe creates a Shoelace, so Shoe must be IDisposable too. And Driver creates Shoe so Driver must be IDisposable. and Bus creates Driver so Bus must be IDisposable and so on. Suddenly my small change to Shoelace is causing me a lot of work and my boss is wondering why I need to checkout Bus to make a change to Shoelace. The Question How do you prevent this spread of IDisposable, but still ensure that your unmanaged objects are properly disposed?

    Read the article

  • How to implement IDisposable properly

    - by Vince
    Hi, I've seen so much C# code in my time as a developer that attempt to help the GC along by setting variables to null or calling Dispose() on classes (DataSet for example) within thier own classes Dispose() method that I've been wondering if there's any need to implement it in a managed environment. Is this code a waste of time in its design pattern? class MyClass : IDisposable { #region IDisposable Members public void Dispose() { otherVariable = null; if (dataSet != null) dataSet.Dispose(); } #endregion }

    Read the article

  • Is this correct for disposing an object using IDisposable

    - by robUK
    I have a class that implements the IDisposable interface. I am using a webclient to download some data using the AsyncDownloadString. I am wondering have I correctly declared my event handlers in the constructor and within the using statement of the web client? And is this correct way to remove the event handlers in the Dispose method? Overrule is this the correct way to use the IDisposable interface? public class Balance : IDisposable { //Constructor WebClient wc; public Balance() { using (wc = new WebClient()) { //Create event handler for the progress changed and download completed events wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); } } ~Balance() { this.Dispose(false); } //Get the current balance for the user that is logged in. //If the balance returned from the server is NULL display error to the user. //Null could occur if the DB has been stopped or the server is down. public void GetBalance(string sipUsername) { //Remove the underscore ( _ ) from the username, as this is not needed to get the balance. sipUsername = sipUsername.Remove(0, 1); string strURL = string.Format("https://www.xxxxxxx.com", sipUsername); //Download only when the webclient is not busy. if (!wc.IsBusy) { // Download the current balance. wc.DownloadStringAsync(new Uri(strURL)); } else { Console.Write("Busy please try again"); } } //return and display the balance after the download has fully completed void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //Pass the result to the event handler } //Dispose of the balance object public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } //Remove the event handlers private bool isDisposed = false; private void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { wc.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.Dispose(); } isDisposed = true; } } }

    Read the article

  • Should I use IDisposable for purely managed resources?

    - by John Gietzen
    Here is the scenario: I have an object called a Transaction that needs to make sure that only one entity has permission to edit it at any given time. In order to facilitate a long-lived lock, I have the class generating a token object that can be used to make the edits. You would use it like this: var transaction = new Transaction(); using (var tlock = transaction.Lock()) { transaction.Update(data, tlock); } Now, I want the TransactionLock class to implement IDisposable so that its usage can be clear. But, I don't have any unmanaged resources to dispose. however, the TransctionLock object itself is a sort of "unmanaged resource" in the sense that the CLR doesn't know how to properly finalize it. All of this would be fine and dandy, I would just use IDisposable and be done with it. However, my issue comes when I try to do this in the finalizer: ~TransactionLock() { this.Dispose(false); } I want the finalizer to release the transaction from the lock, if possible. How, in the finalizer, do I detect if the parent transaction (this.transaction) has already been finalized? Is there a better pattern I should be using? The Transaction class looks something like this: public sealed class Transaction { private readonly object lockMutex = new object(); private TransactionLock currentLock; public TransactionLock Lock() { lock (this.lockMutex) { if (this.currentLock != null) throw new InvalidOperationException(/* ... */); this.currentLock = new TransactionLock(this); return this.currentLock; } } public void Update(object data, TransactionLock tlock) { lock (this.lockMutex) { this.ValidateLock(tlock); // ... } } internal void ValidateLock(TransactionLock tlock) { if (this.currentLock == null) throw new InvalidOperationException(/* ... */); if (this.currentLock != tlock) throw new InvalidOperationException(/* ... */); } internal void Unlock(TransactionLock tlock) { lock (this.lockMutex) { this.ValidateLock(tlock); this.currentLock = null; } } }

    Read the article

  • When should I implement IDisposable?

    - by Bobby
    What is the best practice for when to implement IDisposable? Is the best rule of thumb to implement it if you have one managed object in the class, or does it depend if the object was created in the class or just passed in? Should I also do it for classes with no managed objects at all?

    Read the article

  • Disposing the members that implement IDisposable.

    - by Amby
    In my Dispose methods (like the one below), everytime i want to call someObj.Dispose() i also have a check for someObj!=null. Is that because of bad design on my part? Is their a cleaner way to ascertain that Dispose of all the members (implementing IDisposable) being used in an object is called without having a risk of NullReference exception ? protected void Dispose(bool disposing) { if (disposing) { if (_splitTradePopupManager != null) { _splitTradePopupManager.Dispose(); } } } Thanks for your interest.

    Read the article

  • Time to ignore IDisposable?

    - by Mystagogue
    Certainly we should call Dipose() on IDisposable objects as soon as we don't need them (which is often merely the scope of a "using" statement). If we don't take that precaution then bad things, from subtle to show-stopping, might happen. But what about "the last moment" before process termination? If your IDisposables have not been explicitly disposed by that point in time, isn't it true that it no longer matters? I ask because unmanaged resources, beneath the CLR, are represented by kernel objects - and the win32 process termination will free all unmanaged resources / kernel objects anyway. Said differently, no resources will remain "leaked" after the process terminates (regardless if Dispose() was called on lingering IDisposables). Can anyone think of a case where process termination would still leave a leaked resource, simply because Dispose() was not explicitly called on one or more IDisposables? Please do not misunderstand this question: I am not trying to justify ignoring IDisposables. The question is just technical-theoretical.

    Read the article

  • Using Unity and interfaces, how do I create a concrete class that implements IDisposable

    - by Ryan ONeill
    I have an interface (IDbAccess) for a database access class so that I can unit test it using Unity. It all works fine in Unity and now I want to make the concrete database class implement IDisposable so that it closes the db connections. My problem is that Unity does not understand that my concrete class is disposable because the interface (IDbAccess) cannot implement another interface. So how can I write code like this (pseudo code) so that Unity is aware that it needs to dispose the class as soon as I am done? Using var MyDbAccessInstance = Unity.Resolve<IDbAccess> { } Thanks Ryan

    Read the article

  • How do you reconcile IDisposable and IoC?

    - by Mr. Putty
    I'm finally wrapping my head around IoC and DI in C#, and am struggling with some of the edges. I'm using the Unity container, but I think this question applies more broadly. Using an IoC container to dispense instances that implement IDisposable freaks me out! How are you supposed to know if you should Dispose()? The instance might have been created just for you (and therefor you should Dispose() it), or it could be an instance whose lifetime is managed elsewhere (and therefor you'd better not). Nothing in the code tells you, and in fact this could change based on configuration!!! This seems deadly to me. Can any IoC experts out there describe good ways to handle this ambiguity?

    Read the article

  • IDisposable, does it really matter

    - by adrianm
    Coming from C/C++ a long time ago I still have a habit of ensuring that all resources are cleaned up correctly. I always ensure Dispose is called on IDisposable classes and implement Dispose patterns in my classes containing disposable objects. However, in my environment I'm more or less the only one doing this. Others just don't understand what I'm doing and think my code is more difficult to understand. They just create database connections, open streams etc without calling Close or Dispose. Sometimes they set a local or member variable to "Nothing" at the end of a method (guess their background). My problem is that their code works just as well as mine. Code that over time creates thousands of database connection objects just works. So, ignoring any arguments about code correctness, following guidelines etc, does IDiposable really matter? Has anyone actually ran out of resources from not Disposing objects?

    Read the article

  • Passing IDisposable objects through constructor chains

    - by Matt Enright
    I've got a small hierarchy of objects that in general gets constructed from data in a Stream, but for some particular subclasses, can be synthesized from a simpler argument list. In chaining the constructors from the subclasses, I'm running into an issue with ensuring the disposal of the synthesized stream that the base class constructor needs. Its not escaped me that the use of IDisposable objects this way is possibly just dirty pool (plz advise?) for reasons I've not considered, but, this issue aside, it seems fairly straightforward (and good encapsulation). Codes: abstract class Node { protected Node (Stream raw) { // calculate/generate some base class properties } } class FilesystemNode : Node { public FilesystemNode (FileStream fs) : base (fs) { // all good here; disposing of fs not our responsibility } } class CompositeNode : Node { public CompositeNode (IEnumerable some_stuff) : base (GenerateRaw (some_stuff)) { // rogue stream from GenerateRaw now loose in the wild! } static Stream GenerateRaw (IEnumerable some_stuff) { var content = new MemoryStream (); // molest elements of some_stuff into proper format, write to stream content.Seek (0, SeekOrigin.Begin); return content; } } I realize that not disposing of a MemoryStream is not exactly a world-stopping case of bad CLR citizenship, but it still gives me the heebie-jeebies (not to mention that I may not always be using a MemoryStream for other subtypes). It's not in scope, so I can't explicitly Dispose () it later in the constructor, and adding a using statement in GenerateRaw () is self-defeating since I need the stream returned. Is there a better way to do this? Preemptive strikes: yes, the properties calculated in the Node constructor should be part of the base class, and should not be calculated by (or accessible in) the subclasses I won't require that a stream be passed into CompositeNode (its format should be irrelevant to the caller) The previous iteration had the value calculation in the base class as a separate protected method, which I then just called at the end of each subtype constructor, moved the body of GenerateRaw () into a using statement in the body of the CompositeNode constructor. But the repetition of requiring that call for each constructor and not being able to guarantee that it be run for every subtype ever (a Node is not a Node, semantically, without these properties initialized) gave me heebie-jeebies far worse than the (potential) resource leak here does.

    Read the article

  • Deriving from a component and implementing IDisposable properly

    - by PaulH
    I have a Visual Studio 2008 C# .NET 2.0 CF project with an abstract class derived from Component. From that class, I derive several concrete classes (as in my example below). But, when I go to exit my Form, though the Form's Dispose() member is called and components.Dispose() is called, my components are never disposed. Can anybody suggest how I can fix this design? public abstract class SomeDisposableComponentBase : Component { private System.ComponentModel.IContainer components; protected SomeDisposableComponentBase() { Initializecomponent(); } protected SomeDisposableComponentBase(IContainer container) { container.Add(this); Initializecomponent(); } private void InitializeComponent() { components = new System.ComponentModel.Container(); } protected abstract void Foo(); #region IDisposable Members bool disposed_; /// Warning 60 CA1063 : Microsoft.Design : Ensure that 'SomeDisposableComponentBase.Dispose()' is declared as public and sealed.* public void Dispose() { // never called Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // never called if (!disposed_) { if (disposing && (components != null)) { components.Dispose(); } disposed_ = true; } base.Dispose(disposing); } #endregion } public SomeDisposableComponent : SomeDisposableComponentBase { public SomeDisposableComponent() : base() { } public SomeDisposableComponent(IContainer container) : base(container) { } protected override void Foo() { // Do something... } protected override void Dispose(bool disposing) { // never called base.Dispose(disposing); } } public partial class my_form : Form { private SomeDisposableComponentBase d_; public my_form() { InitializeComponent(); if (null == components) components = new System.ComponentModel.Container(); d_ = new SomeDisposableComponent(components); } /// exit button clicked private void Exit_Click(object sender, EventArgs e) { this.Close(); } /// from the my_form.designer.cs protected override void Dispose(bool disposing) { if (disposing && (components != null)) { // this function is executed as expected when the form is closed components.Dispose(); } base.Dispose(disposing); } } *I note that FX-Cop is giving me a hint here. But, if I try to declare that function as sealed, I get the error: error CS0238: 'SomeDisposableComponentBase.Dispose()' cannot be sealed because it is not an override Declaring that function an override leads to: 'SomeDisposableComponentBase.Dispose()': cannot override inherited member 'System.ComponentModel.Component.Dispose()' because it is not marked virtual, abstract, or override Thanks, PaulH

    Read the article

  • Lifetime issue of IDisposable unmanaged resources in a complex object graph?

    - by stakx
    This question is about dealing with unmanaged resources (COM interop) and making sure there won't be any resource leaks. I'd appreciate feedback on whether I seem to do things the right way. Background: Let's say I've got two classes: A class LimitedComResource which is a wrapper around a COM object (received via some API). There can only be a limited number of those COM objects, therefore my class implements the IDisposable interface which will be responsible for releasing a COM object when it's no longer needed. Objects of another type ManagedObject are temporarily created to perform some work on a LimitedComResource. They are not IDisposable. To summarize the above in a diagram, my classes might look like this: +---------------+ +--------------------+ | ManagedObject | <>------> | LimitedComResource | +---------------+ +--------------------+ | o IDisposable (I'll provide example code for these two classes in just a moment.) Question: Since my temporary ManagedObject objects are not disposable, I obviously have no control over how long they'll be around. However, in the meantime I might have Disposed the LimitedComObject that a ManagedObject is referring to. How can I make sure that a ManagedObject won't access a LimitedComResource that's no longer there? +---------------+ +--------------------+ | managedObject | <>------> | (dead object) | +---------------+ +--------------------+ I've currently implemented this with a mix of weak references and a flag in LimitedResource which signals whether an object has already been disposed. Is there any better way? Example code (what I've currently got): LimitedComResource: class LimitedComResource : IDisposable { private readonly IUnknown comObject; // <-- set in constructor ... void Dispose(bool notFromFinalizer) { if (!this.isDisposed) { Marshal.FinalReleaseComObject(comObject); } this.isDisposed = true; } internal bool isDisposed = false; } ManagedObject: class ManagedObject { private readonly WeakReference limitedComResource; // <-- set in constructor ... public void DoSomeWork() { if (!limitedComResource.IsAlive()) { throw new ObjectDisposedException(); // ^^^^^^^^^^^^^^^^^^^^^^^ // is there a more suitable exception class? } var ur = (LimitedComResource)limitedComResource.Target; if (ur.isDisposed) { throw new ObjectDisposedException(); } ... // <-- do something sensible here! } }

    Read the article

  • A Generic, IDisposable WCF Service Client

    - by Steve Wilkes
    WCF clients need to be cleaned up properly, but as they're usually auto-generated they don't implement IDisposable. I've been doing a fair bit of WCF work recently, so I wrote a generic WCF client wrapper which effectively gives me a disposable service client. The ServiceClientWrapper is constructed using a WebServiceConfig instance, which contains a Binding, an EndPointAddress, and whether the client should ignore SSL certificate errors - pretty useful during testing! The Binding can be created based on configuration data or entirely programmatically - that's not the client's concern. Here's the service client code: using System; using System.Net; using System.Net.Security; using System.ServiceModel; public class ServiceClientWrapper<TService, TChannel> : IDisposable     where TService : ClientBase<TChannel>     where TChannel : class {     private readonly WebServiceConfig _config;     private TService _serviceClient;     public ServiceClientWrapper(WebServiceConfig config)     {         this._config = config;     }     public TService CreateServiceClient()     {         this.DisposeExistingServiceClientIfRequired();         if (this._config.IgnoreSslErrors)         {             ServicePointManager.ServerCertificateValidationCallback =                 (obj, certificate, chain, errors) => true;         }         else         {             ServicePointManager.ServerCertificateValidationCallback =                 (obj, certificate, chain, errors) => errors == SslPolicyErrors.None;         }         this._serviceClient = (TService)Activator.CreateInstance(             typeof(TService),             this._config.Binding,             this._config.Endpoint);         if (this._config.ClientCertificate != null)         {             this._serviceClient.ClientCredentials.ClientCertificate.Certificate =                 this._config.ClientCertificate;         }         return this._serviceClient;     }     public void Dispose()     {         this.DisposeExistingServiceClientIfRequired();     }     private void DisposeExistingServiceClientIfRequired()     {         if (this._serviceClient != null)         {             try             {                 if (this._serviceClient.State == CommunicationState.Faulted)                 {                     this._serviceClient.Abort();                 }                 else                 {                     this._serviceClient.Close();                 }             }             catch             {                 this._serviceClient.Abort();             }             this._serviceClient = null;         }     } } A client for a particular service can then be created something like this: public class ManagementServiceClientWrapper :     ServiceClientWrapper<ManagementServiceClient, IManagementService> {     public ManagementServiceClientWrapper(WebServiceConfig config)         : base(config)     {     } } ...where ManagementServiceClient is the auto-generated client class, and the IManagementService is the auto-generated WCF channel class - and used like this: using(var serviceClientWrapper = new ManagementServiceClientWrapper(config)) {     serviceClientWrapper.CreateServiceClient().CallService(); } The underlying WCF client created by the CreateServiceClient() will be disposed after the using, and hey presto - a disposable WCF service client.

    Read the article

  • Getting rid of nested using(...) statements

    - by Ghostrider
    Sometimes I need to use several disposable objects within a function. Most common case is having StreamReader and StreamWriter but sometimes it's even more than this. Nested using statements quickly add up and look ugly. To remedy this I've created a small class that collects IDisposable objects and disposes of them when it itself is disposed. public class MultiDispose : HashSet<IDisposable>, IDisposable { public MultiDispose(params IDisposable[] objectsToDispose) { foreach (IDisposable d in objectsToDispose) { this.Add(d); } } public T Add<T>(T obj) where T : IDisposable { base.Add(obj); return obj; } public void DisposeObject(IDisposable obj) { obj.Dispose(); base.Remove(obj); } #region IDisposable Members public void Dispose() { foreach (IDisposable d in this) { d.Dispose(); } } #endregion } So my code now looks like this: using (MultiDispose md = new MultiDispose()) { StreamReader rdr = md.Add(new StreamReader(args[0])); StreamWriter wrt = md.Add(new StreamWriter(args[1])); WhateverElseNeedsDisposing w = md.Add(new WhateverElseNeedsDisposing()); // code } Is there anything wrong with this approach that can cause problems down the road? I left the Remove function inherited from the HashSet on purpose so that the class would be more flexible. Surely misusing this function can lead to objects not being disposed of properly, but then there many other ways to shoot yourself in the foot without this class.

    Read the article

  • IDisposable: is it necessary to check for null on finally {}?

    - by BlackTigerX
    In most examples that you find on the web when explicitly not using "using", the pattern looks something like: SqlConnection c = new SqlConnection(@"..."); try { c.Open(); ... } finally { if (c != null) //<== check for null c.Dispose(); } If you do use "using" and look at the generated IL code, you can see that it generates the check for null L_0024: ldloc.1 L_0025: ldnull L_0026: ceq L_0028: stloc.s CS$4$0000 L_002a: ldloc.s CS$4$0000 L_002c: brtrue.s L_0035 L_002e: ldloc.1 L_002f: callvirt instance void [mscorlib]System.IDisposable::Dispose() L_0034: nop L_0035: endfinally I understand why the IL gets translated to check for null (doesn't know what you did inside the using block), but if you're using try..finally and you have full control of how the IDisposable object gets used inside the try..finally block, do you really need to check for null? if so, why?

    Read the article

  • Can't Use Generic C# Class in Using Statement

    - by Eric J.
    I'm trying to use a generic class in a using statement but the compiler can't seem to treat it as implementing IDisposable. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; namespace Sandbox { public sealed class UnitOfWorkScope<T> where T : ObjectContext, IDisposable, new() { public void Dispose() { } } public class MyObjectContext : ObjectContext, IDisposable { public MyObjectContext() : base("DummyConnectionString") { } #region IDisposable Members void IDisposable.Dispose() { throw new NotImplementedException(); } #endregion } public class Consumer { public void DoSomething() { using (new UnitOfWorkScope<MyObjectContext>()) { } } } } Compiler error is: Error 1 'Sandbox.UnitOfWorkScope<Sandbox.MyObjectContext>': type used in a using statement must be implicitly convertible to 'System.IDisposable' I implemented IDisposable on UnitOfWorkScope (and to see if that was the problem, also on MyObjectContext). What am I missing?

    Read the article

  • How to make an IDisposable object a class variable?

    - by Ben Aston
    I am working with Active Directory using C#. Instantiating the PrincipalContext object seems to be expensive, so I'd like to store one in a class variable. When using PrincipalContext as a local variable, I can use the convenient using syntax. When storing an IDisposable object in a static variable, how do I ensure the object is properly disposed of?

    Read the article

  • How do I unit test a finalizer?

    - by GraemeF
    I have the following class which is a decorator for an IDisposable object (I have omitted the stuff it adds) which itself implements IDisposable using a common pattern: public class DisposableDecorator : IDisposable { private readonly IDisposable _innerDisposable; public DisposableDecorator(IDisposable innerDisposable) { _innerDisposable = innerDisposable; } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion ~DisposableDecorator() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) _innerDisposable.Dispose(); } } I can easily test that innerDisposable is disposed when Dispose() is called: [Test] public void Dispose__DisposesInnerDisposable() { var mockInnerDisposable = new Mock<IDisposable>(); new DisposableDecorator(mockInnerDisposable.Object).Dispose(); mockInnerDisposable.Verify(x => x.Dispose()); } But how do I write a test to make sure innerDisposable does not get disposed by the finalizer? I want to write something like this but it fails, presumably because the finalizer hasn't been called by the GC thread: [Test] public void Finalizer__DoesNotDisposeInnerDisposable() { var mockInnerDisposable = new Mock<IDisposable>(); new DisposableDecorator(mockInnerDisposable.Object); GC.Collect(); mockInnerDisposable.Verify(x => x.Dispose(), Times.Never()); }

    Read the article

1 2 3 4 5 6 7 8 9 10 11  | Next Page >