Thursday, July 12, 2012

ClojureCLR with WPF - REPL and Compile

In order to run a ClojureCLR script with a non blocking WPF UI we have the two basic options
  1. in a REPL - being able to modify the window
  2. as console app executable
The solution to both scenarios are not quite obvious if you're not familiar with WPF or the threading models. For WPF and COMInterop the threading model has to be a Single Threaded Apartment. My first thought was to use the documented STAThreadAttribute which the .NET compilers are using. In ClojureCLR .NET attributes can be applied with the meta data syntax ^{}. Either Clojure.Compile.exe isn't aware of the STAThread feature at the moment or I haven't found the option yet. Have to digg into the code later. My first try to apply it to the -main function failed.

Kick starting my approach from Marius Kjehldahl's ClojureCLR post on running a WPF Window in a REPL you'll get option 1. I've shamelessly copied his solution and created my own quick workaround where a new Thread is spawn setting the AppartmentState to STA with the ability to load a .xaml.

For option 1, I created two gists from hist post for the REPL solution with some minor modifications:

For option 2 have a look at the following gist for compiling instructions and some background information regarding the threading model.

UPDATE: Here is a quickfix for the Clojure.Compile.exe allways appending the STAThread attribute to the  main executable. There is the generation from the clojure source file left.

No comments:

Post a Comment