I'm a C# developer having worked with .Net since it was in beta. Before that I mainly worked in C and C++. I have been developing commercial software for more than 20 years. I also mess around with microprocessors, but that's just for fun. I live near Cambridge, England and work from home in my 'silicon shed'.

Blogroll

People who know me understand that I like pretty code. This post describes something that I came up with to make my units tests look more pretty. Say you want to run a unit test on a service, and normally that service would log lots of stuff (using log4net for example). But for the purpose of the unit test you just want to throw away all the log entries. You might use moq, and do something like this:

Ahh, we still have a “null” implementation of the ILog interface, but to me saying “NullOf<log4net.ILog>.Instance“ looks just a bit nicer :-) Better than that, it’s generic, so you can use it on other interfaces too. Null implementations all round then.

I'm working on a lot of multithreaded code at the moment. In the past I have made use of the lock keyword in C#, but I'm not doing that anymore because it is much better to have a timeout. However, I don't like having lots of sections like this in my code:

if (System.Threading.Monitor.TryEnter(objLock, TIMEOUT))

{

try

{

// do stuff here...

}

finally

{

System.Threading.Monitor.Exit(objLock);

}

}

...which is the equivalent of using the lock statement, but with a timeout specified. Still, what I'd like to see in my code is something like this:

lock (objLock,TIMEOUT)

{

// do stuff here...

}

Which would be more pretty. And since I like pretty code, I decided to see how close I could get to that. This is my current solution:

publicstaticclassLock

{

publicstatic T Try<T>(object objLock, int timeout, Func<T> f)

{

if (System.Threading.Monitor.TryEnter(objLock, timeout))

{

try

{

return f.Invoke();

}

finally

{

System.Threading.Monitor.Exit(objLock);

}

}

returndefault(T);

}

publicstaticvoid Try(object objLock, int timeout, Action f)

{

if (System.Threading.Monitor.TryEnter(objLock, timeout))

{

try

{

f.Invoke();

}

finally

{

System.Threading.Monitor.Exit(objLock);

}

}

}

}

So far, that is as close as I can get, it means that I can do two things:

Lock.Try(objLock, TIMEOUT, delegate

{

// stuff here...

});

or, if I need to return a value, then this:

returnLock.Try<int>(objLock,TIMEOUT,delegate

{

// stuff here...

return 0;

});

Because the second example uses generics, then I can return anything I like by specifying the type inside the angled brackets. Now I feel that my code is a lot more prettier which is a nice way to finish off on a Friday.

Recently I needed to open a new WPF window on a new thread. I was helped a great deal by this article, however the window that I needed to open did not have parameterless constructor. In the end, this is the code that I came up with: