.Net 4 introduced the Lazy<T> type which allows you to create an object that can be lazily initialized so that you can delay the creation of large objects, for instance.
However, if your initialization logic has the potential to except at runtime (e.g. time out exceptions reading from some external data source) then you should pay close attention to which constructor you use to create a new instance of the Lazy<T> type. Depending on the selected LazyThreadSafetyMode, exceptions in the initialization code might be cached and rethrown on all subsequent attempts to fetch the lazily initialized value. Whilst this ensures that threads will always get the same result, hence removing ambiguity, it does mean that you’ve got only one shot at initializing that value…
In cases where you need to be able to tolerate occasional initialization errors (e.g. reading a large object from S3 can fail from time to time for a number of reasons) and be able to try again at a second attempt, the rule of thumb is to instantiate the Lazy<T> type by setting LazyThreadSafetyMode to PublicationOnly. In PublicationOnly thread safety mode, multiple threads can invoke the initialization logic but the first thread to complete the initialization successfully sets the value of the Lazy<T> instance.
For example, the following only works under the PublicationOnly mode:
F# provides a slightly nicer syntax for defining a lazy computation:
the Control.Lazy<T> type is an abbreviation of the BCL Lazy<T> type with a Force extension method which under the hood just calls Lazy<T>.Value.
Presumably the above translates roughly to the following C# code:
var x = 10;
var result = new Lazy<int>(() => x + 10);
and the thread safety mode using the Lazy(Func<T>) constructor is LazyThreadSafetyMode.ExecutionAndPublication which caches and rethrows any exceptions caught in the initialization. E.g.:
.Net 4.5 introduced a handy little new method Comparer<T>.Create to aid the creation of bespoke comparers, which is great because it means that you don’t have to define a new Comparer class when it is going to be needed once.
In case you’re wondering, it’s still not possible to define anonymous implementation of interfaces in C#, but with Comparer<T>.Create you can at least create a bespoke instance of IComparer<T> from an anonymous method:
As a side, you can also apply the same technique for other single method interfaces yourself, for instance, if you were happy to ignore the existence of the Zip extension method for the sake of the example, you could define your own Zip extension method which takes in an instance of an IZipper<T, U, V>:
Whilst we’re on the topic of anonymous interface implementation. F# has a nice little feature call Object Expressions, it provides a mechanism for creating anonymous types that are based on existing base type, interface, or set of interfaces, and for the two examples, here’s how that solution might look in F#:
Notice that there’s no need for an explicit implementation class for IZipper<T, U, V> interface at all using Object Expressions and how much less code you end up writing with F#! So seriously, why aren’t you checking out F# already!?
Just a quick note to say that I have updated the JSON serializers benchmark to use the latest Nuget versions of ServiceStack.Text, Json.Net and JsonFX.
I have also included the JSON and BSON serializers from the MongoDB C# Driver in the test, and since BSON is a binary format I have included protobuf-net as a reference since it’s the fastest binary serializer I know of on the .Net platform:
Compared to the last set of results, you can see that the latest version of JsonFX seems have gone much much slower on deserialization, whilst ServiceStack.Text is still the fastest JSON serializer around. The MongoDB C# Driver’s JSON and BSON both held up pretty well in the test too.
In general, when you see async void in your code it’s bad news, because:
- you can’t wait for its completion (as mentioned in this post already)
- any unhandled exceptions will terminate your process (ouch!)
Suppose you have a timer event that fires every once in a while and you want to do some asynchronous processing inside the handler, so you proceed to write something along the lines of:
The fact that your timer event excepted might hurt, that it took your whole process with it is likely to hurt an awful lot more!
Well, what are your options? If you change the handler to return Task instead the code won’t compile because ElapsedEventHandler delegate type specifies a void return type.
Two options springs to mind here.
First, you can always just execute the whole block of code synchronously instead.
This is not ideal because it’s going to block the thread whilst it’s waiting for the asynchronous operation to come back, preventing the thread from being used to do other useful work in the mean time.
If you wish to persist with using async-await and just wish to swallow any exceptions then you can consider option two:
In this case, we’ve simply used a continuation (which fires regarded whether the preceding task had faulted) to swallow any exception that had been thrown by the asynchronous operations.
Hope this helps, and remember, whenever you see async void in your code it should be triggering off your spider senses!
With the official release of .Net 4.5 and Visual Studio 2012, I suspect many .Net developers will be rushing to rewrite their data access or network layers (amongst many many other things!) to take advantage of the new async-await (see the excellent 101 examples here) language feature in C#, which means you’ll likely be working with the Task and Task<T> type an awful lot.
If you have F# code that needs to interop with C# that returns or awaits some task types then you’ve probably already come across the Async.StartAsTask<T> and Async.AwaitTask<T> methods for converting between F#’s Async<T> and Task<T> types. Curiously, there are no equivalent methods on the Async class for converting between Async<unit> and Task types.
So, to fill in the gaps ourselves, here are two simple functions to do just that: