.Net 4 intro­duced the Lazy<T> type which allows you to cre­ate an object that can be lazily ini­tial­ized so that you can delay the cre­ation of large objects, for instance.

How­ever, if your ini­tial­iza­tion logic has the poten­tial to except at run­time (e.g. time out excep­tions read­ing from some exter­nal data source) then you should pay close atten­tion to which con­struc­tor you use to cre­ate a new instance of the Lazy<T> type. Depend­ing on the selected LazyThread­Safe­t­y­Mode, excep­tions in the ini­tial­iza­tion code might be cached and rethrown on all sub­se­quent attempts to fetch the lazily ini­tial­ized value. Whilst this ensures that threads will always get the same result, hence remov­ing ambi­gu­ity, it does mean that you’ve got only one shot at ini­tial­iz­ing that value…

 

LazyThread­Safe­t­y­Mode

In cases where you need to be able to tol­er­ate occa­sional ini­tial­iza­tion errors (e.g. read­ing a large object from S3 can fail from time to time for a num­ber of rea­sons) and be able to try again at a sec­ond attempt, the rule of thumb is to instan­ti­ate the Lazy<T> type by set­ting LazyThread­Safe­t­y­Mode to Pub­li­ca­tionOnly. In Pub­li­ca­tionOnly thread safety mode, mul­ti­ple threads can invoke the ini­tial­iza­tion logic but the first thread to com­plete the ini­tial­iza­tion suc­cess­fully sets the value of the Lazy<T> instance.

For exam­ple, the fol­low­ing only works under the Pub­li­ca­tionOnly mode:

 

F#

F# pro­vides a slightly nicer syn­tax for defin­ing a lazy com­pu­ta­tion:

image

the Control.Lazy<T> type is an abbre­vi­a­tion of the BCL Lazy<T> type with a Force exten­sion method which under the hood just calls Lazy<T>.Value.

Pre­sum­ably the above trans­lates roughly to the fol­low­ing C# code:

var x = 10;

var result = new Lazy<int>(() => x + 10);

and the thread safety mode using the Lazy(Func<T>) con­struc­tor is LazyThreadSafetyMode.ExecutionAndPublication which caches and rethrows any excep­tions caught in the ini­tial­iza­tion. E.g.:

image

Share

.Net 4.5 intro­duced a handy lit­tle new method Comparer<T>.Create to aid the cre­ation of bespoke com­par­ers, which is great because it means that you don’t have to define a new Com­parer class when it is going to be needed once.

In case you’re won­der­ing, it’s still not pos­si­ble to define anony­mous imple­men­ta­tion of inter­faces in C#, but with Comparer<T>.Create you can at least cre­ate a bespoke instance of IComparer<T> from an anony­mous method:

As a side, you can also apply the same tech­nique for other sin­gle method inter­faces your­self, for instance, if you were happy to ignore the exis­tence of the Zip exten­sion method for the sake of the exam­ple, you could define your own Zip exten­sion method which takes in an instance of an IZipper<T, U, V>:

Whilst we’re on the topic of anony­mous inter­face imple­men­ta­tion. F# has a nice lit­tle fea­ture call Object Expres­sions, it pro­vides a mech­a­nism for cre­at­ing anony­mous types that are based on exist­ing base type, inter­face, or set of inter­faces, and for the two exam­ples, here’s how that solu­tion might look in F#:

Notice that there’s no need for an explicit imple­men­ta­tion class for IZipper<T, U, V> inter­face at all using Object Expres­sions and how much less code you end up writ­ing with F#! So seri­ously, why aren’t you check­ing out F# already!? Winking smile

Share

Just a quick note to say that I have updated the JSON seri­al­iz­ers bench­mark to use the lat­est Nuget ver­sions of ServiceStack.Text, Json.Net and JsonFX.

I have also included the JSON and BSON seri­al­iz­ers from the Mon­goDB C# Dri­ver in the test, and since BSON is a binary for­mat I have included protobuf-net as a ref­er­ence since it’s the fastest binary seri­al­izer I know of on the .Net platform:

image

image

Com­pared to the last set of results, you can see that the lat­est ver­sion of JsonFX seems have gone much much slower on dese­ri­al­iza­tion, whilst ServiceStack.Text is still the fastest JSON seri­al­izer around. The Mon­goDB C# Dri­ver’s JSON and BSON both held up pretty well in the test too.

Share

In gen­eral, when you see async void in your code it’s bad news, because:

  1. you can’t wait for its com­ple­tion (as men­tioned in this post already)
  2. any unhan­dled excep­tions will ter­mi­nate your process (ouch!)

 

Sup­pose you have a timer event that fires every once in a while and you want to do some asyn­chro­nous pro­cess­ing inside the han­dler, so you pro­ceed to write some­thing 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 han­dler to return Task instead the code won’t com­pile because ElapsedE­ven­tHandler del­e­gate type spec­i­fies a void return type. Annoyed

Two options springs to mind here.

First, you can always just exe­cute the whole block of code syn­chro­nously instead.

This is not ideal because it’s going to block the thread whilst it’s wait­ing for the asyn­chro­nous oper­a­tion to come back, pre­vent­ing the thread from being used to do other use­ful work in the mean time.

If you wish to per­sist with using async-await and just wish to swal­low any excep­tions then you can con­sider option two:

In this case, we’ve sim­ply used a con­tin­u­a­tion (which fires regarded whether the pre­ced­ing task had faulted) to swal­low any excep­tion that had been thrown by the asyn­chro­nous operations.

 

Hope this helps, and remem­ber, when­ever you see async void in your code it should be trig­ger­ing off your spi­der senses!

Share

With the offi­cial release of .Net 4.5 and Visual Stu­dio 2012, I sus­pect many .Net devel­op­ers will be rush­ing to rewrite their data access or net­work lay­ers (amongst many many other things!) to take advan­tage of the new async-await (see the excel­lent 101 exam­ples here) lan­guage fea­ture in C#, which means you’ll likely be work­ing 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 prob­a­bly already come across the Async.StartAsTask<T> and Async.AwaitTask<T> meth­ods for con­vert­ing between F#’s Async<T> and Task<T> types. Curi­ously, there are no equiv­a­lent meth­ods on the Async class for con­vert­ing between Async<unit> and Task types.

So, to fill in the gaps our­selves, here are two sim­ple func­tions to do just that:

 

Enjoy!

Share