Asynchronous ShowDialog

It is quite common that in our application we use Modal Windows. Now more and more the asynchronous programming model is used pervasively. C# and VB.Net languages even provides a syntactic sugar for them using the async/await feature.

It is desirable that one could expect to await the ShowDialog unfortunately, ShowDialog is a synchronous API. By definition, synchronous API can’t be await ed; It doesn’t makes sense either trying to await a synchronous method.

However, you can make the synchronous method “awaitable” by wrapping it in a Task — you do it using Task.Run or Task.Factory.StartNew. That executes the given method asynchronously in ThreadPool thread making a synchronous operation asynchronous.

Sounds great right, So it is just a matter of  wrapping ShowDialog call in Task.Run to make it asynchronous. Let’s do that.

Your synchronous code below

Becomes this

Alright, We’re done right? Yes, except that it won’t work –we’re done with it.

This could work for any other synchronous method, but not for anything which is related to UI. UI elements typically have “Thread affinity”. Which means they have to be dealt with the thread which it was created. Otherwise, You’ll get an InvalidOperationException well known as “cross thread exception”.

In this case we could move the creation of window inside the Task.Run(with some trick) and fix the violation of thread affinity requirement. But that will not yield you what you would expect. Window will not be shown as Modal window of the owner. etc.

It turns out that we can’t show the UI in worker thread(at least gracefully). It is evident that we must call the ShowDialog method from the user interface thread only. But the method being synchronous, preventing us from awaiting it. Are we back to the place where we started? No way around it?

Well, we can satisfy the requirement of calling the method in user interface thread itself and asynchronously also. Thanks to Dispatcher.BeginInvoke which makes it possible.

That is a different API which isn’t awaitable; nevertheless msft gifted us the TaskCompletionSource<T> type which could wrap anything in Task.

With just two more lines of code, it is possible

We could make this code as a reusable piece of code. Maybe a nice extension method as below

Then you could call it as

Note that the code is about Wpf, but it doesn’t matter much. You can pretty much do the same in any UI technology with very little change. For example, in winforms, you’d use Form instead of Window, DialogResult instead of bool?  and Control.BeginInvoke method instead of Dispatcher.BeginInvoke.

That’s about it. Hope you enjoyed the post. Let’s make everything asynchronous :). Have fun.

C# compiler Fails to Fail-Fast

If title didn’t made sense,  I believe at least the post will 🙂

When you invoke a method on a null instance in  C# NullReferenceException will be thrown unlike C++/CLI which allows instance methods to be called with null references.

C# compiler does this with the help of callvirt opcode. As we saw earlier that the compiler emits call opcode when it can prove that the object reference is not null.

Compiler is trying to be smart and optimizes the callvirt to call opcode as we saw in my last post. I agree; compiler is smart, but not smart enough.

Yeah, compiler made a brave assumption that new operator will never return null. But that’s a false assumption. New operator returns null in this corner case.

Consider my following contrived example:

Clearly the above code shows that the code explodes in middle of the method(where this pointer is dereferenced) with NullReferenceException and not at the very beginning of the method call itself.

The C# compiler failed to Fail Fast and thus the title 🙂


C# compiler doesn’t always emits a virtual call (callvirt)

MSIL provides two ways to call a method in IL level with opcodes call and callvirt respectively.

In a nutshell call opcode calls the method with early binding where as callvirt makes the late bound call(method will be chosen at runtime rather than compile time).

Apart from the early/late binding difference, callvirt also checks if the instance in which the method is being called is null, if so –It will throw NullReferenceException.

If you do a web search you could easily reach some blog posts, forums which says that C# compiler  always emits callvirt for even non virtual methods. Me too tend to believe that was true; it turns out that it is not.

You have been mislead

Hell no! You have been mislead. Although C# compiler usually emits callvirt for non virtual methods, it does emits call opcode when it can prove that the object reference is not null.

Technically there is no reason for the compiler to emit callvirt for non virtual methods or sealed methods as we already know that late binding isn’t going to make any difference because you can’t override a sealed or non virtual method. But compiler emits callvirt just for the sake of getting free null checks by the runtime.

Why does that matters? Why can’t we allow instance methods to be invoked with null instance? Fail Fast is better than allowing you to call a instance method with null reference and surprising you at some point with NullReferenceException where this reference is accessed.

IL code for the above snippet(only Main method) is as follows

Above snippet shows a case where C# compiler emits a call opcode for instance method.

Yeah C# compiler is being smart[1] here by emitting call opcode because it can prove that the instance can never be null. So that it couldn’t waste the cpu cycles in testing for null which we already know it isn’t.

As soon as I discovered this myself, googling little bit turns out that I’m not the first guy to discover it.

1:C# compiler is smart, but not smart enough.

Oh that Iterators!! They are damn lazy.

You might know about Iterators which was introduced way back with C# 2.0. It provides a nice way to iterate a collection incredibly easy with yield keyword.

If you think you knew about Iterators already, let’s play a guessing game. Follow the code snippet below and guess what is the output of the program.

What do you expect that the above code will do when executed?

  1. Prints Program completed successfully” to the console.
  2. Crashes with ArgumentOutOfRangeException.
  3. Something else ?

Wait! Before you take a guess read the code again carefully. There is a chance that you could have overlooked.

Ok, If you have guessed the answer is A then you probably have good understanding of the Iterators; Yes it is the correct answer. I don’t have much to say for you. This post is for readers who took a wrong guess as B. I don’t even think someone would have chosen C, If you did — Sorry for confusing you by adding C as an option here.

At this point can you guess what could be the reason behind this program just prints  Program completed successfully” to the console given that previous line which calls the method GetGumbers(-1) should have thrown exception?

Yes you guessed it right. Iterators are damn lazy; this is what called as deferred execution. Compiler will transform the code inside the Iterator method to a state machine which doesn’t changes the semantics of the code.  When you  call IEnumerator.MoveNext() state machine will advance its state to yield next result. You will be calling it implicitly if you’re using foreach statement. Enumerable.ToArray() or Enumerable.ToList() can also do that. I don’t want to repeat the implementation details here and bore you; if you’re curious about the implementation details of Iterator blocks you will find comprehensive article of Jon Skeet very helpful.

In short Iterator blocks starts executing only when the first call to IEnumerator.MoveNext() has been made.

If I were to ask you a question “Is LINQ Lazy ?” you would probably say “Oh yes LINQ is lazy, It defers the execution, blah blah blah” without even knowing how.

Yes you’re absolutely right that LINQ is lazy but how? Because most of  the methods defined in LINQ is implemented using Iterator blocks.  Because the Iterators are lazy –LINQ is lazy.

Have you ever peeked into the implementation details of LINQ methods and wondered why there are pair of methods for each operation one is public part of the API and another is private with “Iterator” suffix ? You can see {Where, WhereIterator}, {Union, UnionIterator}, {Select, SelectIterator}. If you observed properly you could even notice that public methods validates the input and calls private Iterator method and  XXXIterator method doesn’t validates any argument. Can you guess why? At this point you should be able to guess.

As illustrated with the code sample above the laziness of Iterator blocks will give you surprise when exception  is thrown within the Iterator blocks; They are not thrown until the first call to IEnumerator.MoveNext() has been made. This is the reason why you should always validate the arguments in a separate method other than Iterator method.


What you see is not what gets compiled always. It is very common to overlook the code which uses iterator blocks even if you understand it very well. Take some care while reading code with Iterator blocks –you might overlook otherwise.

Breaking the CLR Type Safety

As you might have already heard .Net is type safe. Specifically talking CLR provides type safety at runtime, some .Net languages (example: C#) work with CLR to provide type safety at compile time.

So what does the term type safe mean?

Let’s find what Wikipedia says:

In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behavior caused by a discrepancy between differing data types for the program’s constants, variables, and methods (functions), e.g., treating an integer (int) as a floating-point number (float). Blah blah blah..

Ok, Now we know that type safety has something to do with preventing the programmer from accessing the type as other than what it is.

Well, C# and CLR are pretty good in this, they work together to push you into the Pit of success. But, you need to be very careful when working with unsafe code. Unsafe code is a different world in which you lose all the type safety, memory safety, security etc. So, clearly chances of making mistakes in unsafe code is greater than safe code(code which doesn’t uses unsafe).

We’re not going to look at unsafe code here. There is one trap I can see without using unsafe code at all. It is not so common, but there it is.

You probably have learned union in academics while learning C and C++, but, in C# you probably don’t need this if you’re writing pure managed code, no Interop.  Some of you might not even know that union do exist in .Net world, but they do exist.

I write managed code, To be honest, I’ve never found a use case for union in .Net(at the time of writing), I mean pure managed code, no Interop.

What this post has to do with Union?  As we know that unions share same memory location to store multiple fields(one at a time), that’s where the trap is. Yes, CLR won’t stop you falling into the trap in this case, i.e you could break the type safety provided by CLR using unions. May be break isn’t the right word,  you could call it as a caveat to be aware of. It doesn’t matter what you call, but there’s something to be aware of.

In above program we create a new instance Union and set the Builder field to new StringBuilder. We’re not creating any  instances of String and assigning to Text field, but you can access it. That’s the beauty of unions.

We’re interpreting the StringBuilder as if it is String which also means that something terribly went wrong.

Ideally as a managed programmer you would expect CLR to throw InvalidCastException but above program erroneously  prints some number as String.Length and StringBuilder as the type of the object. If you recall, this clearly violates the definition of type safety from Wikipedia which we skimmed earlier.


This is not to say that CLR isn’t type safe rather it is possible to write erroneous code with C# even without unsafe context. So be careful while dealing with unions in .net.