Never Work With Scientists or Engineers

Forget never working with children or animals. Never work with Scientists or Engineers.

Picture the scene, dear reader; the air is being turned blue with the kind of language usually reserved for the rugby scrum. Things are being thrown.

A calming voice comes from a distant room enquiring what the problem might be. I respond using “language” that mounting the picture in the frame has not gone as well as I had anticipated, it’s not quite central. I may have used the word “disaster”. I can’t recall what the other words were but I seem to recall them being quite short and decidedly pointy.

“But you can fix it,” comes that calming voice again, “you can fix anything.” I take a deep breath, think for a bit and conclude that yes, I can fix it.

There then follows a few minutes of calm and concentration before once again the demons are unleashed, the air turns blue again and more everyday household objects find themselves travelling at unnatural speeds towards various hard surfaces.

“Problems?” enquires the calming voice.

“Yes, ” I reply. You will understand of course that my actual reply was somewhat longer than this but there are international treatise preventing me from disclosing the full transcript. I then continue to explain the cause of my frustration, “have you ever tried to cut 1/4 of a millimetre off the side of a piece of A4 card? It’s impossible!”

It was at that point it hit me, I had a steel ruler on top of a piece of card, both clamped to a cutting mat and I was using a razor blade to trim off a tiny amount to correct an error that only I was ever going to know was there. It was pointless, I should have just put the card in the frame and forgotten about the tiny mistake.

That 1/4mm level of passion, that level of attention to detail is entirely the sort of thing that’s required if you’re an engineer that is, say, responsible for ensuring that 999 (911 ,112)  calls get dealt with correctly (which I am). When mounting a picture however it’s more like an anti-skill, a trait that does more harm than good.

Intlerocked.Exhange and the Atomic Option

Developers are now having to deal with concurrency issues far more than we ever have in the past. Our languages are evolving more and more features (like the Parrallel.* class in C#) that allow us to take advantage without too much pain.
These are great, but they’re not always the answer and they don’t negate the need to understand the fundamental issues of concurrent programming. This is in fact the very subject that this blog started with several years ago...

Today I’d like to talk about Interlocked.Exchange. Its purpose it to exchange two variables in an atomic way. It’s the atomic nature of the exchange that’s the important factor here, it means that nothing can catch the exchange in an incomplete state. It’s either completely one value or completely another value.

Thread Safe Exchange

The significance of this becomes evident when we consider the traditional method of exchanging two variables.

var spare = first;
first = second;
second = spare;

This is not thread safe. The problem is that a second thread could interleave into the first. Consider the following path of execution. Let’s assume the value of first is 5 and the value of second is 10. The table shows the values of the variables as two threads interleave.

Thread Code first second spare 1 spare 2
1 var spare = first; 05 10 05
1 first = second; 10 10 05
2 var spare = first; 10 10 05 10
1 second = spare; 10 05 05 10
2 first = second; 05 10 05 10
2 second = spare; 05 10 05 10

Oh dear… that didn’t work, did it?

If we’d used Interlocked.Exchange we wouldn’t have the problem, because the exchange is atomic no interleaving can take place, the first thread will finish then the second will take over.

Thread Safe Changes of Scope

When it gets really interesting though is the fact that Interlocked.Exchange returns the original value.

public static T Exchange(
    ref T location1,
    T value)
    where T : class

The beauty of this is that we can use this to change scope. There’s a wholly unsafe pattern that gets used in Dispose handlers all the time:


class Blah: IDisposable
{
    SomeDisposableType someObject;

    ...

    public void Dispose()
    {
        if(someObject != null)
        {
           someObject.Dispose();
           someObject = null;
        }
    }
}

It’s possible that two threads could interleave between the null check and someObject being assigned to null, resulting in someObject being disposed twice.

Alternatively…

public void Dispose()
{
    var myCopy = Interlocked.Exchange(ref someObject, null);
    if(myCopy != null)
    {
        myCopy.Dispose();
    }
}

What the Interlocked.Exchange does here is to set someObject to null in the object scope and return its (former) value to myCopy which is in the method scope.
If two threads call Dispose at exactly the same moment, then both of them will succeed in setting the value of someObject to null. In the case of the thread that calls Interlocked.Exchange first, it will return the original value of someObject to its myCopy and set someObject to null. When the second thread calls Interlocked.Exchange it will return the value that the first thread set someObject to, that being null. It will then proceed to set someObject to null again.
The effective is that someObject is set to null twice, but only one of the threads gets the original value of someObject, so only one will pass the null check and only one will call Dispose on someObject.

Note that this isn’t a good Dispose pattern fullstop however. Microsoft have written some guidelines.

This scope switching trick can be useful in other places too. Consider if you’re writing a log file of some description. Writing an ever-expanding log file causes problems, it’s good to have a cut-off and write a new one every so often. A common method is to write one file per day of the week.

public class LogWriter : IDsiposable
{
    StreamWriter writer;
    public string FilePath {get;set;}
    ...

    public void WriteLog(string s)
    {
        writer.WriteLine(s);
    }

    public void StartNewDaysLog()
    {
        var newWriter = new StreamWriter(FilePath + DateTime.Now.DayOfWeek.ToString() + ".log", false);
        var oldWriter = Interlocked.Exchange(ref writer, newWriter);
        if(null != oldWriter)
            oldWriter.Close();
    }
    ...
}

With this implementation multiple threads can safely call WriteLog continuously. When StartNewDaysLog is called a new StreamWriter is set up ready to go, then the two are switched in an atomic fashion. Nothing can catch this out half way through the switch – as far as anything calling WriteLog is concerned one entry was written to one file and the next to another: it’s seamless.
After the switch, StartNewDaysLog is left with the old StreamWriter which it then has to Close (which in turn calls Dispose).

Conclusion

Interlocked.Exchange is a surprisingly useful little tool. Its plain usage – to simply exchange a value in a thread safe way is useful, but where it really comes in handy is in its ability to replace a value and return the original one into a narrower (thread safe) scope. This is particularly handy if you need to move or consume something in a simple way that doesn’t imply graduating to a mechanism such as ReaderWriterLockSlim or SemaphoreSlim.

Callback Trace Listener

lightSo you know about the Trace facility in System.Diagnostics, right? If not then you should because it’s really rather handy. It provides a set of static methods that you can call to write out trace information to any number of connected “Listeners” which you can define in code or in config.
The default trace listener writes to the Win32 OutputDebugString stream, you can view this in Visual Studio’s “Output” window or using a viewer such as Sysinternals DebugView.

Sure if you need more extensive logging and tracing then you should look to something like log4net, but if your requirements are simple then System.Diagnostics.Trace and System.Diagnostics.Debug are really handy.

Anyway, that’s not the point of this article.

Quite often I end up writing non-production apps – little gizmos for this or that – which could do with informing the user of what’s going on via some sort of rolling log on the UI.

So I wrote this tiny little class to help.

public class CallbackTraceListener : TraceListener
{
    public event Action<string> WriteToOutput;

    public override void Write(string message)
    {
        if (null != WriteToOutput)
            WriteToOutput(message);
    }

    public override void WriteLine(string message)
    {
        Write(message + Environment.NewLine);
    }
}

It’s a Trace Listener just like the one that writes to OutputDebugString. You need a little bit more code to make it work, in the initialisation of the your application you need to register an instance of it as a trace listener…

public MainWindow()
{
    var uiTracer = new CallbackTraceListener();
    uiTracer.WriteToOutput += UiTracer_WriteToOutput;
    uiTracer.Name = "UITraceListener";
    Trace.Listeners.Add(uiTracer);
    Trace.WriteLine("Debug window initialised");
    Trace.WriteLine("Ready...");
    InitializeComponent();
    ...
}

Now every time you use any of the Trace methods that write output, the UiTracer_WriteToOutput callback will be called with the string that’s written. You can add the strings to a ListBox, or put them through any other kind of processing you want.
It’s a really simple and useful way to subscribe to up your own Debug/Trace stream.

Let’s Go to the Winchester…

Don't Vote Leave...It hit me about 4pm today that although I’ve done a lot of myth debunking on social media and directed people to well supported articles, I haven’t actually expressed my opinion on the EU Referendum.

It was inevitable.

In the UK we’ve had something like 8 years of economic stagnation. Whenever something like that happens there are certain things that history tells us will follow. People will lose faith in the politicians of the day and start looking for answers elsewhere. New movements will spring up saying that they have the answers. The things they say are always the same, we need to break free of regulation, bureaucracy and red tape, we need to empower the individual, the problems are caused by some external entity (usually immigrants) and most of all we need to take our country back and make it great again.

Right now that’s Farage, Trump, Le Penne, Marusik, etc.

These things are not the answers because the sad, soul crushing reality is that there are no answers right now.

Our problems are not caused by our membership of the EU, Boris Johnson said as much in 2013, I’m paraphrasing but basically “the only thing leaving the EU would achieve is to make Britain face up to the fact that its problems are not caused by the EU.”

Our problems are caused by a combination of the poor performance of the global economy and our own mistakes and inadequacies. We have consistently failed to invest in public services and infrastructure. We have failed to properly regulate the financial sector. Time and time again we have put short term gains before the necessary long term strategy. These things and others are the cause of our current malaise, not our EU membership.

I can’t believe it, but I basically agree with what Boris said in 2013 (I disagree on many of the details, BTW).

Leaving the EU will not bring us any significant gain, even in the areas that the Leave campaign are targeting.

If we stay in the Free Trade Area (like Norway and Switzerland) we will have to accept almost all of the EU’s rules, including the free movement of people.
At the moment we’re one of the big 3, with France and Germany we’re the most influential countries in Europe. We’d lose that so we’d effectively lose sovereignty – because at the moment we have some control.

It would also make democracy worse as at the moment we all have a voice through the UK government and through our MEPs. We’d lose that.

I’m sure I needn’t point out that the proposed points system on immigration is highly unlikely to be acceptable to the EU if we remain in the Free Trade Area.

So we’re talking about a substantial divorce from Brussels, that’s the only way we can get any freedom of movement on immigration. Sovereignty and democracy are more complex arguments but neither would be a cavalcade of success. They’re both pretty minor gains if you analyse them in depth (NATO, WTO, IMF, UN, House of Lords, FPTP etc).

The problem with this is that even the Leave campaign recognise that this would hit our economy hard. Unemployment would rise, the welfare bill would rise and the economy would slow down long term. The slower the economy the less money there is flowing around the less the government gets in tax, the less we can afford to pay out in welfare and services. Even a tiny slowing would eclipse the EU membership fee from the government’s budget so what we’re facing here is not investment in services like the NHS, but even more and ever more severe cuts at a time when we really, really don’t need that because half our problems are caused by our failure to invest in the past.

The numbers can only work if we remain in the Free Trade Area which gains us nothing but a tiny bit of pride. It’s pointless.

There’s no quick fix for the situation we’re in, it’s going to be a long hard slog but there will be an upturn. When there is there’ll be more money flowing in the economy so the government will get more in tax and we can afford to put right some of the mistakes of the past.

If we stay we can hold our heads high, we’ll be at the top table of the EU, the largest market in the world, a major player on the world stage. If we leave we seriously risk becoming an ever more irrelevant and isolated sad little island.

I am proud to be from Suffolk, proud to be English, proud to be British. I care about this country and I care about its place in the world, so I will be voting to remain a member of the European Union.

 

[You will appreciate this is rather a hasty hack of an article, I haven’t really had time to properly reference it and I’ve glossed over a lot of detail that I would have included if I had longer]

I Was Growled at by a Car Lion

Samson Car Lion

Samson the Car Lion

Meet Samson, he’s a Car Lion. His job is protect the car he’s in against any unwanted attention. Currently he lives on the dash of our hauling, ferrying and carrying car – a Honda Jazz (aka Fit) called Delilah.

Samson is a very happy Car Lion, Delilah is very spacious inside, so he has a large territory. The Jazz/Fit also has a considerable amount of glass in the cabin and the cab-forward design means that he has a large and very prominent area to prowl and make sure that all is in order.
He also likes window stickers and we keep him well supplied with them.

Samson's Favourite Snack

Samson’s Favourite Snack

Now let me introduce you to another Car Lion with a less fortunate story. You see it came to pass that we needed to buy a second car. We didn’t really know what we needed or how long we’d need it for so we played it safe and bought a Ford Fiesta. We called the car “Rory” because he didn’t need a name, he was only “tempoRory” [sic].

It may surprise you to learn that Ford Fiestas are often supplied without a Car Lion to protect them. So we went to Africa Alive and came back with this gorgeous little fellow. It was clear that this Car Lion was far too big to live on Rory’s dash though, so we came to an arrangement that he would live on the back seat.

Rory's Car Lion

Rory’s Car Lion

He liked to sleep a lot when he wasn’t on duty so he liked it there – it was warm and soft. Being somewhat larger than Samson he wasn’t too worried about being on higher ground because he could easily jump up and growl at any potential miscreant. It’s true that Rory wasn’t as roomy as Delilah is, but it had some additional creature comforts such climate control and more importantly an MP3 player – because Car Lions have got to have their choonz.

I have to admit that we didn’t really think about the Car Lion in Rory. He was there, doing his job and he seemed to be happy enough. It didn’t occur to me that we might be neglecting him – we had after all given Rory a name and we weren’t intending to keep Rory long. The poor Car Lion didn’t even have a name.

It was when we sold Rory that it finally dawned on me. As I took him from the back seat the full horror hit me – the back seat. The car we replaced Rory with is a much more permanent affair, she’s called Mina and, well, the problem is rather obvious.

Mina

Mina

So there were two things I needed to make up to our sadly anonymous Car Lion. The first was easy for me – although Mina is very snug she’s a convertible which means that she makes an excellent home for a Car Lion. He can stay safe and warm when he needs to or go out and prowl as far as he likes. Being in the front seat however there was a problem – the car only has two seatbelts and he’s too big to have roaming around when we’re both in the car. So I made him a little seatbelt of his own.

Car Lion All Strapped In

Car Lion All Strapped In

The second problem is more difficult – the obvious name for a Car Lion that protects a car called Mina is Jonathan, but Mina wasn’t his first car so I think calling him Jonathan is unfair, we need to respect the very good work he did protecting Rory. So what do we call him?


It was somewhere in the region of 23 minutes before someone suggested Liony McLionface, which was rather longer than I expected. Other suggestions so far include:

  • Cecil (but I’d have to sew a bullet-hole through him somehow)
  • Cedric
  • Clarence (how rude!)
  • Denn (long story)
  • Don / Vito, as in Don Car Lione (badoom-tish!)
  • Kenneth
  • Kieran (another long story)
  • Leo
  • Lionel
  • Liono
  • McGrath
  • Numair  (Arabic – “panther”)
  • Simba
  • Roan Miry
  • Vlad

In the end we decided on a name, so meet Vito Car-Lione… He’d like to be your friend, and that’s an offer you can’t refuse.
Vito Car-Lione

Too Much Information!

Broken Seat ClampWe, the cycling advocates, want more people to cycle. We dedicate our time to producing useful material for new cyclists and people who are thinking of taking up cycling. Are we barking up the wrong tree though?

Articles on how to get the right bike, what clothes to wear, how to pick the right helmet, how to ride in traffic, how to ride in the countryside, what tools to take, how to maintain a bicycle, what the best sub-miniature lightweight pump for mid-distance touring rides is…

It’s all meant well. It’s all meant to try to help people. If I put myself in the position of someone thinking of taking up cycling though I see something different. What I see is a lot of articles telling me how complicated cycling is. I need to make sure I have the right bike, the right clothing, the right helmet, the right tools. I need to remember how to ride in traffic, how to ride at a roundabout, when to take the lane and when not.

I recently cycled to an event where I met a lot of new people. We were all waiting around, talking about this and that and I started to become aware that there were a lot of people listening to me and I was being asked a lot of questions about how I came to cycle there.

No, I haven’t changed my clothes – I cycled here in this pair of smart trousers and shirt. No, I don’t have cycling shorts on underneath that would be really uncomfortable.

No they’re not special cycling trousers or a special cycling shirt. They’re just good quality, comfortable clothes.

No, there aren’t any showers and I don’t need a shower because I cycled here at a sensible pace. It wasn’t a workout.

About 37 years.

Actually I didn’t wear a helmet today. Yes they do help in certain types of crash but they’re not some kind of magic bullet that will save you if you’re run over by a train. They do reduce the risk, yes. Sometimes I do wear a helmet, I’m not quite sure how I decide when to and when not to.

No actually, most helmets have vents in them, vents large enough that you can lock the helmet to the bike to the bike rack.

I’m wearing a blue and white spotty shirt. That’s not a naturally occurring phenomenon in most environments.

It’s locked to the bike rack at the front of the building. No, it’s not an expensive bike. Yes it is actually covered by my house insurance.

It didn’t look like rain so I didn’t bring a coat. It’s not a freezing cold day so if it rains on the way home it’s no biggie. I’ll just change when I get there.

No, a couple of miles isn’t far.

No, it’s a couple of miles. That really isn’t far enough to cause any kind of problem that would need that sort of cream.

No I’m not super-fit.

No, I actually avoided that and took the cycle path that goes across the docks. I have cycled round there before though and it’s not as scary as you might think. Remember you’re higher up on a bike so you can generally see better than cars can.

No, actually most drivers are really good. There are always a few idiots and yes they’re far scarier when you’re on a bike. No actually, I’ve not had a serious crash on the road in all the 37 years I’ve been cycling.

No, I don’t have a spare tube or a puncture repair kit. I’m in town, there are cycle shops and even if there weren’t it’s a couple of miles. I can walk. Punctures are uncommon anyway, modern city [puncture resistant] tyres are pretty good at stopping them.

If I’m right and this was a representative sample of the public then we have a bit of an issue. The message that we want to get across is that cycling is fun, practical, cheap, easy, safe and something that anyone can do.

The message that we seem to be getting across is that it’s expensive, complicated, dangerous and requires a Lycra Licence.

So what can we do about it? I don’t think we should start un-publishing the articles that are out there – many of them are really good and contain a lot of useful information. I think the problem stems from the fact that most of us cycling advocates are sports and leisure cyclists. We invest time and money into cycling because it’s a hobby. We want to share that with other people and that’s great, but we’re bringing the wrong character. We’re bringing the person that loves to cycle 25 miles through the rolling hills to that great little café by the brook that does the proper tea and the millionaire shortbread with that really thick caramel layer.

It’s an intoxicating image, but distances like 25 miles are going to put the willies right up a potential new cyclist. The idea of being 25 miles from home with a machine they don’t understand and can’t maintain is pretty scary too. Group rides are terrifying because they’re afraid they’ll hold everyone up and Lycra – which many seem to believe is mandatory – requires way more (body) self confidence than most people have.

Yes we’re selling the dream, but it’s too big, too far away for most people to grasp. They will get there, if they want to get there, but we need to start smaller.

For instance, many of us aren’t just leisure or sports riders. We also use a bike to pop to shops or to commute to work. We don’t do that in Lycra riding a Santa Cruz Nomad. OK, so most of us don’t use a battered 2nd hand beater bike either, but we could do. We need to try to get across the the joy of just being able to grab the bike and go – the freedom that comes with not being strapped into a little metal stress box, even on short journeys. We need to place cycling as a part of everyday life, something that normal people can easily do and as a cheap, effective and safe way of enriching your existence.

For want of a better way of putting it, we need to humanise cycling. Make it normal, accessible, everyday. We need to place them in the saddle.

We need to talk about things like how social cycling is – and I don’t mean meeting other cyclists because the idea of a cafe full of people in cycle gear chatting about the latest carbon fibre seat clamp scares the hell out of most new cyclists. I mean things like my neighbour, the keen gardener who always waves and says “Hi” when I pass.

Cycling is about connecting with the environment, being part of life.

Climate control, cruise control, stereo, sat nav, cooped up in a little sound proof reinforced cage. That’s about isolating you from the environment, from the journey, from life. Driving is the nearest thing you can get to posting yourself somewhere, all wrapped up nicely in a neat package to be delivered. Sometimes that’s just how it has to be but when it doesn’t we have the opportunity to be part of something so much more fulfilling.

Out of bread? Just grab the bike and go, past the flowers in Mary’s garden that always smell so nice at this time of year, the fields we can see from the top of the hill that stretch for miles and miles all different colours, the little cottage that we’d definitely buy if we had the money and then play the game of can I make it down into the village without having to peddle again?
Walk into the village shop where Carol lets you know that they’ve just got in some of that bread you really like… Go past that cafe, it smells good so just turn round, lock the bike up outside and pop in for tea and a cake because… because it’s Tuesday!

You don’t need to ride 100 miles, you don’t need a £4000 bike, bib-shorts and a comprehensive track toolkit to do that, to be that person, to be that engaged with life.

You just need a bike.

That is the message we need to get across.

Connectorum Reseatorum

Compact!

Compact!

Last time I talked about De Morgan’s law which I learnt in electronics but still use in computer science.

Today I want to talk about a revered piece of arcane wisdom, a ritual handed down from electronics master to apprentice according to the strictest laws of tradition. It’s called “Connectorum Reseatorum” and I just used it to raise my compact camera back from the dead.

What they don’t want you to know is that you don’t actually need any complex electronics expertise to perform the ritual. All you do is take the case off and then one-by-one take each connector apart, clean the contacts (surgical spirit / rubbing alcohol works quite well) and then put the connector back together again.

It’s surprising how many electronics faults are just down to a bad connection and can be fixed simply by cleaning contacts and removing dirt.

Break the Line, Change the Sign

Ipswich Civic College [(c) EADT]

Ipswich Civic College [(c) EADT]

Shirt and tie, green tank top, brown jacket with leather patches on the elbows and horn rimmed spectacles. The image of my college maths tutor yelling “break the line, change the sign!” is still burnt into my brain.
Nevertheless De Morgans’s Law is one of those things from my days as an electronics research technician that’s still useful today – so it was worth it.

I needed to change an if statement around. Originally it was like this;

if (null == cert || !cert.HasPrivateKey)
   doMainPart()
else
   doElsePart()

But I wanted to switch the main and else part around, so I wanted to reverse the result of the condition. I could have done this…

if ( !(null == cert || !cert.HasPrivateKey))

But instead I employed De Morgan’s Law. To invert the meaning of the entire condition the first step is to invert the meaning of each individual term of the condition. So:

  • null == cert becomes null != cert
  • !cert.HasPrivateKey becomes cert.HasPrivateKey

The second step is to change the operators that combine the terms, so OR becomes AND and vice-versa.
Thus (null != cert && cert.HasPrivateKey) gives the exact opposite result to (null == cert || !cert.HasPrivateKey).

if (null != cert && cert.HasPrivateKey)
   doElsePart()
else
   doMainPart()

It’s really easy to tie yourself in knots with this kind of stuff, remembering De Morgan’s law can save a lot of heartache.


If you’re wondering why it’s “break the line, change the sign” this is because of the way boolean logic is written is electronics: if you want to invert the meaning of something you don’t put a ! in front of it, you draw a line over the top of it.
So our condition would have started as:

null == cert || cert.HasPrivateKey

We then want to invert the entire operation, so we draw a line right over the top…

null == cert || cert.HasPrivateKey

Now we apply De Morgans’s Law, we break the line and change the sign.

null == cert && cert.HasPrivateKey

Of course the two inversions on the right-hand side cancel each other out, so we finish with:

null == cert && cert.HasPrivateKey

Of in C#

null != cert && cert.HasPrivateKey

Social Personality

Singapore

Singapore

I made a mistake when I joined The University of Hull back in 2008. I don’t mean that joining university was a mistake, it was one of the best career decisions I’ve made. I made a mistake with the way I used social media.
Part of the role at The University was to be an ambassador, to represent and promote the university and the field of computer science. “No problem,” I thought, “I’ll just use my existing social media accounts.” That was the mistake.

It led to two problems. The first is that my online persona changed. I suddenly became aware that I used the account for professional purposes. That changed the image of the account, it became my professional persona and it became very difficult for me to be the person that my friends know outside of the professional environment.
The second problem is that I started adding professional “friends” and followers.  That reinforced the first problem.
I went from someone who’d been very active on social media to someone who only posted the most carefully filtered content.

If you are a professional you have to be somewhat circumspect, once you’ve hit the “send” button you’ve lost an element of control – it’s out there. Even friend-locked posts and old blog articles can resurface at inopportune moments.

At the last interview I was at one of the interviewers let slip something that they couldn’t have known unless they’d read my blog – and not only that but it wasn’t in the most prominent article either. As a professional your online presence matters.

Fortunately the Victorian image of professionalism is now fading. I maintain however that a professional image is important. It’s about giving your clients and peers confidence that when you turn up to work you’re going to do a good job. For instance, if your social media streams contain a disproportionate amount of pictures and stories of you partying with your friends to all hours that’s going to damage your professional credibility.
A balance still needs to be maintained.

For myself however I no longer work for The University, in fact being an ambassador for computer science is no longer an official part of my job at all. So you’d think it would be easy for me to rectify those mistakes I made back when I joined The University and revert my social media personas back to being more like the real me. You’d think that. It appears to be proving more difficult than I thought, however.

Avoid Constructors that Throw Exceptions

Even ones in the CLR itself…

It’s well know that throwing exceptions in constructors is a bit dodgy (mainly because of possible memory leaks), but things recently got a bit weird.

It worked fine on my machine, however on my colleague’s machine Visual Studio’s unhandled exception dialog kept popping up. After he hit the continue button everything seemed to work OK, but it was still unnerving.

To cut a long story short I’d written something a bit like this[1]

        private async static Task<TcpClient> GetConnectedClient()
        {
            try
            {
                return await Task.Run<TcpClient>(() =>
                {
                    return new TcpClient("127.0.0.1", 80);
                });
            }
            catch(SocketException ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

That particular overload of the TcpClient constructor tries to open a connection and throws a SocketException if it fails. The exception should be marshalled through the await to the catch, but it was all going a bit strange.

So I changed it to something a bit like this[1] and it all started to behave properly.

        private async static Task<TcpClient> GetConnectedClient()
        {
            try
            {
                var client = new TcpClient();
                await client.ConnectAsync();
                return client;
            }
            catch(SocketException ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

Underneath the bonnet (or hood, if you’re not British) ConnectAsync starts a Task to manage the older BeginConnect asynchronous mechanism. Nevertheless, exceptions throw in this scenario are marshalled properly with no weirdness.

Now ultimately both versions of the code seem to work correctly, but what is clear is that there is something different about the exception handling in constructors. So I’d recommend avoiding not just avoiding throwing exceptions in your own constructors but if you can, avoid using constructor that throws an exception.


[1]In order to make the point clear I’ve simplified these examples to the point where, as code, they’re not terribly useful in their own right. I certainly wouldn’t recommend using these as any kind of template.