C# things that make us happy

Sometimes our lives as programmers get a bit easier, Microsoft has launchedlaunched C# 7.0 some time ago. Here are a few examples of the things that made our lives a lot easier.

The microsoft page has better explanations, the code below is just random code from my project. These examples are only intended to outline some of the new features.

Pattern matching

Can be rewriten as:

Using the underscore we can ignore variables, which keeps the compiler (and resharper) happy:
DoSomething(out String variable1, out String _)
Which brings us the pleasure of inline variable definition as well as ignoring unused ones.

It can also create funny code (introducing underscores in useless places):

Tuples
While we have had basic tuples for a long time they grew up and gave us a weapon against the useless class/structs to perform returns (or way to many out variables).

Keep in mind that a tuple is a struct!

Switch statements with patterns
While switching still isn’t available on primitive types it sure improves our lives a lot:

The nature of C# locking issues explained

Sometimes in the life of a programmer everything seems peachy, C#/DotNet provide relatively easy multi threading capabilities which 99.9% of the time work just fine as explained everywhere online.

However when things get a bit serious as these online explanations tend to be off by a small bit, only that small bit creates havoc….

Imagine having to debug code within a lock() statement that crashes with exceptions like “Collection was modified; enumeration operation may not execute” which seemingly bypass any locking in place.
These are not fun to deal with as everyone will for some reason stubbornly tell you that that is not possible and you are simply lacking a lock somewhere and just moving on like they have just shed divine light.

First of all lets get the common misconception cleared that it is impossible for a single thread to execute code in parallel and even worse that events will always be fired with a new thread affinity. This is just plain wrong!

Create a simple empty form with the following code in the shown event:

And paste the following somewhere below:

If what everybody proclaims is right this code should just lock up the UI and neatly print “A”, “B” in sequence when triggered.
This is where the bad news starts, it doesn’t, simply clicking the button a few times very easily prints “A”, “A”, “B”, “B”.
So with a few lines of code we have disproved two very stubborn myths in one blow.

Now for a somewhat more sensible approach:

This properly locks up the UI as expected (it’s example code, not release code) and can even be used for some more interesting purposes when multi threading.

Please don’t be like all the other assholes online who proclaim that this doesn’t happen in normal production code (or even worse that a simple lock() should always be sufficient as events have different thread affinities).
Simply imagine a simple asynchronous communication protocol between two programs or a server and a client, having simple locks can seriously fuck up your day with some long debugging ahead.

DotNet simple and effective profiling

There is one thing all programmers experience at one point or another, performance issues… One might use simple break points to get a coarse idea of the problem locations or when things get really frustrating a stopwatch with several measurement points.
But even that gets frustrating when there are lots of problem areas and it soon turns into a cumbersome practice which we all loathe.

But nothing beats some good old fashioned scripting to create a more elegant solution:

Simple invoke:

More complex invoke:

Next up the extension method, sometimes it’s better to itterate a function a “few” times in order to get a better idea:

Simple invoke:

More complex invoke:

Although it won’t provide you with some of the nice graphs, heatmaps or other goodies some external applications might offer, it will save a lot of time and annoyance.

PNGCrush all

Some programs are great to use but are annoying when it comes to bulk operations they are just too cumbersome, PNGCrush is one of them.
Don’t get me wrong, I really like this program (and actually use it quite often), but it needs a bit of spice to be more useful in our busy daily lives. I don’t want to figure out the syntax every usage and windows “scripting” is just to unreliable.

DotNet to the rescue!, if there is one thing this framework is useful for it’s fast and reliable programming, so a simple CLI helper is quickly formed.

  • Can easily be adapted for other programs/use cases
  • Launches one PNCrush instance per core
  • Displays files that will be processed
  • Displays neatly formatted results
  • Finds the best available PNGCrush executable (version and architecture)
  • Works with DotNet 4.5.2 and newer, older versions require some tinkering (although I don’t see valid reasons to remain on any older version)
  • Could be converted to .AsParallel() LinQ, but where is the fun in that?

PNGCrush-All

Calling Synchronous Methods Asynchronously

Using the BeginInvoke function is way to much fun and something that entry level C# programmers get their hands on fairly quickly. That doesn’t mean it doesn’t have its pitfalls as most don’t bother to read the documentation.

The Microsoft article clearly states:

  • No matter which technique you use, always call EndInvoke to complete your asynchronous call
  • EndInvoke blocks the calling thread until it completes

In situations where a blocking call is not a problem it is a quick and easy fix, but in most situations it just becomes tedious to clean up after yourself.

Using the code is easy to:

It isn’t the cleanest of solutions, it spoils a whole thread so it might not be the best solution for very heavy situations (bulk loading invokes works way better in those cases). But it does alleviate most of the occasional BeginInvoke calls.