About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

Thanks Again Edmug.Net
Presentation's Galore
Spreading the Mojo
And If you want a more robust timer.....
Quick and Dirty Timing
Why Locking On This May Not Be The Best Idea
Finding Great Developers

Archive

Blogroll

 Agile Developer Venkat's Blog
 Ayende @ Blog
 B#
 Barry Gervin's Software Architecture Perspectives
 Boy Meets World
 Brad Abrams
 Canadian Developers
 Christopher Steen
 Claritude Software News
 Clemens Vasters: Enterprise Development and Alien Abductions
 Coding Horror
 Coding in an Igloo
 Dare Obasanjo aka Carnage4Life
 Darrell Norton's Blog [MVP]
 David Hayden [MVP C#]
 Don Box's Spoutlet
 Eric Gunnerson's C# Compendium
 EZWeb guy: Jeffrey Palermo [C# MVP]
 Fear and Loathing
 Generalities & Details: Adventures in the High-tech Underbelly
 Greg Young [MVP]
 Greg's Cool [Insert Clever Name] of the Day
 IanG on Tap
 Ingo Rammer's Weblog
 ISerializable - Roy Osherove's Blog
 James Kovacs' Weblog
 Jason Haley
 Jean-Luc David
 Jeremy D. Miller -- The Shade Tree Developer
 JetBrains .NET Tools Blog
 Jimmy Nilsson's weblog
 John Bristowe's Weblog
 John Papa [MVP C#]
 Jon Skeet's Coding Blog
 JonGalloway.ToString()
 Jump the Fence or Walk Around
 Lambda the Ultimate - Programming Languages Weblog
 Larkware News
 Lutz Roeder
 Marquee de Sells: Chris's insight outlet
 Martin Fowler's Bliki
 Mike Nichols - SonOfNun Technology
 MSDN Magazine - .NET Matters
 MSDN Magazine - All Articles
 OdeToCode Blogs
 Onion Blog
 Planet TW
 Raymond Lewallen [MVP]
 Rockford Lhotka
 RodMan's Corner
 Roger Johansson's blog
 Sahil Malik - blah.winsmarts.com
 Sam Gentile's Blog
 Scott Bellware [MVP]
 Scott Hanselman's Computer Zen
 ScottGu's Blog
 secretGeek
 Service Station, by Aaron Skonnard
 Signum sine tinnitu--by Guy Kawasaki
 Stephen Toub
 Steve Eichert's Blog
 Steven Rockarts
 The Blog Ride
 The Coding Hillbilly
 The Daily WTF
 TheServerSide.net: News
 Tim Gifford
 Vance Morrison's Weblog
 you've been HAACKED

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

 Friday, September 29, 2006
Friday, September 29, 2006 1:27:41 AM (Mountain Standard Time, UTC-07:00) ( Presentations )

Tonight I presented at the Edmonton .Net User Group. Due to a last minute scheduling error (through no fault of the user group), we were left without a room to host the event. That is where the awesome folks from DevStudios stepped up to the plate and provided us with their amazing facilities to host the event. I had never even heard of DevStudios before tonight, and I was completely floored by the setup they have going there. They are currently hiring for Senior Developers, so I you are interested in looking at the Edmonton market, I am sure they would love to talk to you (looks like a great place to work).

I talked about Model View Presenter, among other things. I will be the first to attest that I was very much all over the map in this presentation. Another reminder to myself that sometimes I need to tunnel in on the topic I am supposed to be delivering on. The user group was gracious enough to let me ramble on and sometimes squeeze out the odd bit of code.

Once again, thank you to the Edmonton .Net User Group for having me out to speak. Thanks to DevStudios for providing us with facilities and equipment for the evening. And thanks to Donald,Tom, and Dave for the after event banter!!

Hopefully I'll be back in a couple of months!!

Comments [3] | | # 
 Thursday, September 28, 2006
Thursday, September 28, 2006 7:22:19 AM (Mountain Standard Time, UTC-07:00) ( )

Tonight I have the honor of returning to speak at the Edmonton .Net User Group. The group voted and it looks like people want to see more about Model View Presenter (Passive View, Supervising Controller). I am also going to see if I can sneak in some discussions around enterprise design patterns.

On Saturday, I will also be attending/presenting at the Edmonton Code Camp. If you are going to be in the area, and do not mind hanging out with a bunch of geeks on your Saturday, come down and check out the sessions.

Comments [1] | | # 
 Tuesday, September 26, 2006
Tuesday, September 26, 2006 1:22:39 PM (Mountain Standard Time, UTC-07:00) ( )

Kevin Squires just sent me a link to check out Mojopac. Needless to say, I am pretty blown away by the potential for this software. Are you a developer who is tired of configuring your world just the way you want it when you move to a new PC. This looks like it might solve that and a host of other issues dev's typically face working between multiple PC's.

If you see me come to a presentation in the near future and find me asking any willing participant to donate their laptop, it would solely to be to show off the potential of this software.

I just picked up a brand new Western Digital Passport drive, based off a friends recommendation. This is the perfect device with which I can "free myself from my PC"!!

Get your Mojo on!!!

Comments [2] | | # 
 Friday, September 22, 2006
Friday, September 22, 2006 7:56:07 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 )

In my last post I created a simple class that wrapped around the Stopwatch class in the Framework. If you require a more robust implementation for your needs, check out the timer that Vance Morrison has created. His implementation allows for collecting stats from individual iterations as well as some other interesting features.

Comments [0] | | # 
 Wednesday, September 20, 2006
Wednesday, September 20, 2006 4:24:31 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

There are many times when you are coding up a solution that you want to get a quick idea for how long a given operation is taking. A common first attempt at this is the following:

 

[Test] public void ShouldTimeMethodUsingOldSchoolMethod() { DateTime startTime = DateTime.Now; someClass.MethodToTime(); Console.Out.WriteLine(DateTime.Now.Subtract(startTime).Milliseconds); }

This test should be self explanatory. You set a start time, invoke a method, output the difference between the current time and the start time. So this is all well and good (I'm not even bringing up the issue of timer resolution), but anytime you want to quickly time an operation you will be duplicating yourself. Remember the DRY principle, it will guide you toward much more maintainable codebases.

Remembering the DRY principle, you start to think of ways to encapsulate the concept of a StopWatch in your codebase. If you are in .Net 2.0, the framework has already taken care of this for you with the addition of the Stopwatch class in the System.Diagnostics namespace. If you are still in .Net 1.1, and want an equivalent to the 2.0 Stopwatch, then head over to Jeff Atwood's blog and take a look at his Stopwatch implementation. Using either class, you retrofit you code to take advantage of its functionality:

  

[Test] public void ShouldTimeMethodUsingFrameworkStopwatch() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); MethodToTime(); stopwatch.Stop(); Console.Out.WriteLine(stopwatch.ElapsedMilliseconds); }

As you can see this takes us a step closer to being able to quickly time methods (for quick curiosity). This still seems a bit verbose for my liking. Anytime I want to time a method using this technique I have to:

 

  • Instantiate a stopwatch
  • Start the stopwatch
  • Invoke the method to be timed
  • Stop the stopwatch
  • Output the duration

The only variant in those steps is the method that is going to be invoked (operation to perform). Anyone who knows me, will tell you that I stress the value of eliminating duplication. Let's eliminate the duplication by introducing a new layer of abstraction:

 

public class MyStopwatch : IDisposable { private Stopwatch internalStopwatch; public MyStopwatch() { internalStopwatch = new Stopwatch(); internalStopwatch.Start(); } public void Dispose() { internalStopwatch.Stop(); Console.Out.WriteLine(internalStopwatch.ElapsedMilliseconds); } }

 Notice the use of the IDisposable interface. With this class in place, my previous method now changes to this:

[Test] public void ShouldTimeMethodUsingCustomStopwatch() { using (new MyStopwatch()) { someClass.MethodToTime(); } }

 

Ahh, duplication be gone. Ok, so what if we now want the ability to time a method executing a certain number of times. We could do this:

  

[Test] public void ShouldTimeMethodExecutingACertainNumberOfTimeWithLoopAndCustomStopwatch() { using (new MyStopwatch()) { for (int i = 0; i < 10; i++) { someClass.MethodToTime(); } } }

Again, this is something that is often done a lot of times, so why not take advantage of the class we have created and use accordingly (requires some refactoring):

 

public class MyStopwatch : IDisposable { public delegate void MethodToTime(); private readonly MethodToTime methodToTime; private int numberOfTimesToInvokeMethod; public MyStopwatch(MethodToTime methodToTime):this(methodToTime,1) { } public MyStopwatch(MethodToTime methodToTime, int numberOfTimesToInvokeMethod) { this.methodToTime = methodToTime; this.numberOfTimesToInvokeMethod = numberOfTimesToInvokeMethod; } public void Dispose() { TimeMethodInvocation(); } private void TimeMethodInvocation() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < numberOfTimesToInvokeMethod; i++) { methodToTime(); } stopwatch.Stop(); Console.Out.WriteLine(stopwatch.ElapsedMilliseconds); } }

As you can see, the MyStopwatch class has undergone a serious facelift. To construct an instance of this, you now have to specify a delegate that points to the method you want to invoke!! You can also optionally specify a number of times you want the method to run. Here is a sample demonstrating how to use the upgraded class:

     

[Test] public void ShouldTimeMethodExecutingACertainNumberOfTimesUsingCustomStopwatch() { new MyStopwatch(someClass.MethodToTime,10).Dispose(); }

Now we are getting somewhere!! Although, I am not sure if I like the fact that the client of the stopwatch has to either use it in a using block, or explicitly call dispose (as in the last example), in order to receive timing details. How about exposing a couple of static methods on MyStopwatch: 

 

public static void Time(MethodToTime methodToTime) { Time(methodToTime, 1); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod) { new MyStopwatch(methodToTime,numberOfTimesToInvokeMethod).Dispose(); }
 

Which leads to a much more convienient usage syntax of:

 

[Test] public void ShouldTimeMethodANumberOfTimesUsingConvenienceMethods() { MyStopwatch.Time(someClass.MethodToTime); MyStopwatch.Time(someClass.MethodToTime,10); }

The nice thing about the convenience methods, is that there is no question about whether or not the client will get its output, as the static methods are ensuring that dispose is getting called on the object. And from my perspective, it eliminates the need for a completely static class (which I am not a big fan of).

 

If you are a fan of static classes (which depending on what you are doing, could become the bane of your developer existence), you could also use the following Stopwatch implementation (which ends up being a lot more compact):

  

public class StaticStopWatch { public delegate void MethodToTime(); public static void Time(MethodToTime methodToTime) { Time(methodToTime, 1); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < numberOfTimesToInvokeMethod; i++) { methodToTime(); } stopwatch.Stop(); Console.Out.WriteLine(stopwatch.ElapsedMilliseconds); } }

And of course, to top it off, if you want to allow for a more flexible mechanism of outputting the results you could do this:

 

public class StaticStopWatch { public delegate void MethodToTime(); public static void Time(MethodToTime methodToTime) { Time(methodToTime, Console.Out); } public static void Time(MethodToTime methodToTime,TextWriter output) { Time(methodToTime, 1,output); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod) { Time(methodToTime, numberOfTimesToInvokeMethod, Console.Out); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod,TextWriter output) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < numberOfTimesToInvokeMethod; i++) { methodToTime(); } stopwatch.Stop(); output.WriteLine(stopwatch.ElapsedMilliseconds); } }

Notice the convenience methods that will pass in the Console.Out as the TextWriter to use. This leaves you the ability to pass in your own TextWriter; if you want to,for example, write to a file.

I hope the "timing" of this blog entry was good for you, and that it helped spark you brain with new ideas for implementing your own (ad-hoc) timers in your applications.

Comments [2] | | # 
 Tuesday, September 19, 2006
Tuesday, September 19, 2006 10:02:25 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

Ever since .Net came on the scene, developers have been able to "easily" add multithreaded features to their codebases. I say "easily" because even in .Net, multithreading is something that lots of developers are still not completely comfortable with, or understand well enough to take advantage of it without the pitfalls commonly associated.

Take a look at a code fragment for a class I want to have used in a multithreaded environment (note that in this code fragment, the code that takes advantage of invoking methods on the Console object is not particularly thread-safe, but for the purpose of demonstrating work being done ignore it!!).

 

public class NotSoSafeConsumer : IConsumer { public void DoSomething() { lock(this) { Console.WriteLine("DoSomething"); Thread.Sleep(8000); } } public void DoSomethingElse() { lock(this) { Console.WriteLine("DoSomethingElse"); Thread.Sleep(8000); } } }

Notice that I am locking on this. Here is a sample console app that demonstrates utilizing this class from multiple threads:

 

 

public static void Main() { LockAndWorkWith(new NotSoSafeConsumer()); Console.ReadLine(); } private static void LockAndWorkWith(IConsumer consumer) { Thread firstMethod = new Thread(consumer.DoSomething); Thread secondMethod = new Thread(consumer.DoSomethingElse); firstMethod.Start(); secondMethod.Start(); firstMethod.Join(); secondMethod.Join(); Console.Out.WriteLine("Finished"); }

If you run the code you will notice that it behaves as expected. Ok, JP, what's the point!! Here is all that it takes to break this code:

  

private static void LockAndWorkWith(IConsumer consumer) { lock (consumer) { Thread firstMethod = new Thread(consumer.DoSomething); Thread secondMethod = new Thread(consumer.DoSomethingElse); firstMethod.Start(); secondMethod.Start(); firstMethod.Join(); secondMethod.Join(); Console.Out.WriteLine("Finished"); } }

Notice that the only change that I made was to add the lock statement around the consumer that is passed into the method. Once I have done that the method has acquired a lock on the consumer object. So when the consumer inside of its own method, tries to lock on itself, it cannot acquire the lock as it is already owned.

This happens because when you are taking advantage of locking on "this" you are basically saying I want to lock critical sections of my code using a global locking construct (this), that is available to any object that can access "this"(the object in question). Here is another implementation of the IConsumer that will not suffer from the safe problems as the NotSoSafeConsumer:

 

 

public class SafeConsumer : IConsumer { private object lockObject = new object(); public void DoSomething() { lock(lockObject) { Console.WriteLine("DoSomething"); Thread.Sleep(8000); } } public void DoSomethingElse() { lock(lockObject) { Console.WriteLine("DoSomethingElse"); Thread.Sleep(8000); } } }

If I replace the code in the main method with the following:

 

public static void Main() { LockAndWorkWith(new SafeConsumer()); Console.ReadLine(); }

You will notice that the code now works. I have made no changes to the LockAndWorkWith method, it is still acquiring a lock on the object itself. The object is unaffected by this now because it is using a private locking construct that no other class has access to.

There are lots more interesting locking mechanisms available in .Net such as Mutexes, Semaphores, WaitHandles etc. A large percentage of people have their needs satisfied by taking advantage of the Monitor class, which can actually provide all of the functionality of the other classes when used properly. A larger percentage of people accomplish their simple locking schemes by making use of the lock keyword. If you are going to do that, I suggest making the small change required to protect your "mutex" from the outside world.

Comments [1] | | # 
 Wednesday, September 06, 2006
Wednesday, September 06, 2006 8:20:47 PM (Mountain Standard Time, UTC-07:00) ( )

Joel has done it again, with a brilliant post that discusses a process for finding and securing awesome developers. It is a thought provoking read; and it sounds like he definitely has the right idea with his approach to drawing people toward Fog Creek software.

Comments [1] | | #