I just tested it, and it works.
At first I got the impression that is was unreliable (to the same degree as what I had created), but after some experimentation it showed that I needed a pull-up resistor at the output of the MIDI port. (In fact you should use an optocoupler for this.)
But with a pull-up resistor it works now without any problems. So I think my code would work also, but this code is more compact, so I will keep using it.
Many thanks again!