NUnit keeps tcp connections alive - c#

Simple class using a TcpListener (this is just to present the problem, by no means this class makes any practical sence):
using System;
using System.Net.Sockets;
namespace NUnitTcp
{
public class Foo
{
TcpListener lst;
public Foo()
{
lst = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 9090);
}
~Foo()
{
lst.Stop();
}
public void Start()
{
lst.Start();
}
public void Stop()
{
lst.Stop();
}
}
}
A simple application that uses Foo:
using System;
namespace NUnitTcp
{
class Program
{
static void Main(string[] args)
{
Foo f = new Foo();
f.Start();
}
}
}
This application runs fine, port is released as soon as the app ends and the app can be run again! Even without the destructor in Foo this would still happen!
A simple NUnit test with Foo:
using System;
using NUnitTcp;
using NUnit.Framework;
namespace NUnitTcpTests
{
[TestFixture]
public class TcpTests
{
[Test]
public void test1()
{
Foo f = new Foo();
f.Start();
Assert.True(true);
}
}
}
This test will run just once in the NUnit GUI thingy. Any subsequent execution of that test will throw an exception informing us that the port is in use. The NUnit GUI restart will release the port.
Would you consider this a bug? Seems to me like one...
CORRECTION - the test will randomly throw an exception, for me about 70% of the time.

The garbage collector is non-deterministic. It only closes promptly in the first example because the process exits. I strongly suggest you implement IDisposable instead of using a finalizer, then you can use:
using(Foo f = new Foo())
{
f.Start();
Assert.True(true);
}
safe in the knowledge that it will close promptly.
With something like:
public void Dispose()
{
if(lst != null) lst.Stop();
lst = null;
}

Port is in use until your Foo instance will not be collected by Garbage Collector. Also thus you have finalizer defined, it will require two garbage collection for finalizer to be called (Foo will be moved to finalization queue during first garbage collection, and finalizer will be possibly called during second garbage collection). If you want to be sure port will be released, I suggest you to close stop manually Foo in TearDown method:
private Foo _foo;
[SetUp]
public void Setup()
{
_foo = new Foo();;
}
[Test]
public void test1()
{
_foo.Start();
// Assert
}
[TearDown]
public void TearDown()
{
if (_foo != null)
_foo.Stop();
}
Also it would be nice to implement IDisposable on your Foo class, because it uses unmanaged resources, which should be released:
public class Foo : IDisposable
{
TcpListener lst;
public Foo()
{
lst = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 9090);
}
public void Dispose()
{
lst.Stop();
}
}

Related

How to programmatically force C# to run ' Destructors ' Immediately? [duplicate]

This question already has answers here:
When should I create a destructor?
(8 answers)
Closed 6 days ago.
I'm dealing with an C# windows form application and I need to run class destructor immediately right after destroying my object .
using System;
namespace Test
{
class TTTest
{
public TTTest()
{
Console.WriteLine("Constructor Called");
}
~TTTest()
{
Console.WriteLine("Destroyed called");
}
}
class Program
{
static void Main(string[] args)
{
TTTest obj1 = new TTTest();
TTTest obj2 = new TTTest();
obj1 = null;
obj2 = null;
Console.ReadKey();
}
}
}
If I run this code ... The result will be :
Constructor Called
Constructor Called
and wont be :
Constructor Called
Constructor Called
Destroyed called
Destroyed called
I want to force compiler to run Garbage collector and I can do that by :
GC.Collect
But I want to run Destructor of each class right after destroying each object without calling GC.Collect() in my routines automatically.
Is there any way ?
I need a good way to destroyed any things right after destroying my object , and do not repeat GC.Collect() again and again .
Thanks for any help.
In c# you would implement such a mechanic using Dispose().
class TTTest : IDisposable
{
public TTTest()
{
Console.WriteLine("Constructor Called");
}
public void Dispose()
{
Console.WriteLine("Dispose called");
}
}
class Program
{
static void Main(string[] args)
{
using (TTTest obj1 = new TTTest())
using (TTTest obj2 = new TTTest())
{
Console.ReadKey();
}
}
}

How to call a Singleton's Destructor When Closing Console Application?

I am a little confused if my current application is doing what I require. I want to basically just create a Singleton and when the Console application is terminated, call the Destructor of the Singleton. I have it so the Console App will terminate when I hit ENTER, but I am not exactly sure if this is doing what I want. When I put a breakpoint in the Destructor, it gets hit ONLY when I do hit Enter. I just want to make sure what I am doing is correct and if not, how can I change it.
Here is my Singleton:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() { }
~Singleton()
{
Console.WriteLine("Destructor Called."); // Breakpoint here
}
}
And in my Main:
public static void Main(string[] args)
{
Singleton instance = Singleton.Instance;
Console.ReadLine();
}
EDIT: Got it working, thanks!
You can't call destructor programmatically. It is always called by .NET CLR in garbage collection. However for your singleton, I would strongly discourage use of destructor.
Recommendation is to implement IDisposable interface, if you want to release any resources. Or any custom interface implementation will work as well to release any resources, because its weird to implement IDisposable on Singleton.
public sealed class Singleton : IDisposable
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() { }
~Singleton()
{
Console.WriteLine("Destructor Called."); // Breakpoint here
}
void IDisposable.Dispose()
{
Console.WriteLine("Dispose Called.");
GC.SuppressFinalize(this);
}
}
class Program
{
static void Main(string[] args)
{
Singleton.Instance.ToString();
((IDisposable)Singleton.Instance).Dispose();
GC.Collect();
}
}

Is it OK to stop a thread from the owning objects Dispose method?

Here is a simple example:
class MyClass : IDisposable
{
bool working;
public MyClass()
{
working = true;
Thread t = new Thread(Worker);
t.Start();
}
void Worker()
{
while(working)
{}
}
public void Dispose()
{
working = false;
}
}
Is it okay to do this ? Will Dispose() even be called while the thread is still running? If not, how to better do it ?
Dispose will not be called unless you call it, either explicitly or through enclosing MyClass instantiation in using statement.
Will Dispose() even be called while the thread is still running?
It can be called like:
using (MyClass m = new MyClass())
{
System.Threading.Thread.Sleep(2000);
}
So once the using block ends, it will call the Dispose method in your class.
(Although your variable should be volatile to indicate that the field might be modified by multiple threads)
But the important thing to note is, that there is no magical thing about Dispose, even the using statement translates into try-finally , where Dispose is explicitly called in the finally block.
You shouldn't rely on that your Dispose method will be called.
You can wrap you class instance with WeakReference. The thread should stop its work once the reference is garbage collected.
class MyClass : IDisposable
{
class CancellationSignal
{
WeakReference _reference;
public bool IsWorking { get { return _working && _reference.IsAlive; } }
volatile bool _working;
public CancellationSignal(WeakReference reference)
{
if (reference == null) throw new ArgumentNullException("reference");
_reference = reference;
}
public void Signal()
{
_working = false;
}
}
CancellationSignal _cancellationSignal;
public MyClass()
{
_cancellationSignal = new CancellationSignal(new WeakReference(this));
Thread t = new Thread(Worker);
t.Start(_cancellationSignal);
}
static void Worker(object state)
{
var s = (CancellationSignal)state;
while (s.IsWorking)
{
//...
}
}
public void Dispose()
{
_cancellationSignal.Signal();
}
}
Personally I prefer to avoid using finalizers but I still have to say that another solution would be calling Signal in finalizer (and then you can remove WeakReference stuff):
~MyClass()
{
_cancellationSignal.Signal();
}
Notice that _working is declared as volatile. You can also use ManualResetEventSlim or even CancellationToken instead.
In both approaches (WeakReference and finalizer) you have to avoid passing this reference to Thread (because it would prevent your class instance from being garbage collected) therefore I added a CancellationSignal class and marked Worker as static.

Rhino-Mocking ExpectationViolationException

I started to use Rhino-Mocks and Unit-Tests a few days ago so I'm new in this.
I created a disposable class like this:
public class SomeClass : IDisposable
{
private bool _disposed;
public SomeOtherClass ObjB { get; private set; }
public SomeClass(SomeOtherClass b)
{
ObjB = b;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
// set all properties to null
ObjB = null;
// ...
}
_disposed = true;
}
}
and the unit test which should check if the dispose was done correctly:
[TestFixture]
public class SomeClassTests
{
[Test]
public void ShouldDisposeCorrectly()
{
var classB = MockRepository.GenerateStrictMock<SomeOtherClass>()
SomeClass smth;
using (smth = MockRepository.GenerateStrictMock<SomeClass>(classB))
{ }
smth.Expect(p => p.ObjB).Should().BeNull();
}
}
Now when I start the test it throws the following error:
Rhino.Mocks.Exceptions.ExpectationViolationException : SomeClass.Dispose(True); Expected #0, Actual #1.
Can you help me to find the missing step? :-)
What are you actually wanting to test here?
That the compiler produces the correct code when you use a using statement? Seems fairly pointeless.
Or that your class implements IDisposable? You could do that with a simpler test.
Or that your disposal routine correctly disposes of the resources? This test doesn't check that. You could completely empty the Dispose(bool) method and the test you say you want to write would still pass.
Better to check that ObjB is null after the object has been disposed and that any other things which should be done in the dispose method have been. What you want to check is that the behaviour when you dispose your object is what you expect

MEF Object Lifecycle

I have a single class called Foo:
using System;
using System.ComponentModel.Composition;
namespace MefTest
{
[Export]
internal class Foo
{
public Foo()
{
Console.WriteLine("created foo");
}
~Foo()
{
Console.WriteLine("Dead");
}
}
}
It's created as such:
using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MefTest
{
internal class Program
{
public static void Main()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
//EDIT: my problem, this returns Lazy<Foo> not Foo. Since I didn't call foo1.Value it was never actually created
var foo1 = container.GetExport<Foo>();
container.ReleaseExport(foo1);
foo1 = null;
GC.Collect();
Console.Read();
}
}
}
But it never seems to get disposed. I tried adding an IDisposible interface to it without any luck.
How can I ensure this gets cleaned up correctly? I thought that ReleaseExport would do it but the destructor never gets called, so it never appears to be cleaned up.
I've read http://mef.codeplex.com/wikipage?title=Parts%20Lifetime but I can't seem to see the problem with the above code.
The problem you have is that Foo is a shared export. If you want it disposed as is, you can implement IDisposable on it and then call Dispose on the container.
The other option is to mark Foo as non-shared which will result in ReleaseExport calling the Dispose method on it.
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
internal class Foo
{
public Foo()
{
Console.WriteLine("created foo");
}
~Foo()
{
Console.WriteLine("Dead");
}
}
The above is explained pretty well in the "Scoped operations and early reclaim of resources" section of the link you provided. Just remember that if you don't supply a PartCreationPolicy attribute, the export is shared by default.

Categories