Accessing the UI Thread with Tasks in F#

I have a Windows Forms program written in F# that can deploy a code base to n number of sites at once (you select the sites you would like to deploy to and it goes off and completes a number of tasks (backing up current sites, various unpacking and moving of files etc... ).

Once you start it, it begins it's merry journey and begins to update the UI with what has happened. At the moment this method of updating the UI is not pretty because the threads I am doing the work on can't update the UI so I perform some fiendery to make that happen (don't ask).

I knew there was a better way using some newer .NET features but I just hadn't got round to having a fiddle yet. I have now found that if you use the built in Task class but break your code up in a nicer way and then chain the tasks together you can then pass the correct context into the task that you want to talk to the UI.

Here's a little script to give you a feel for it. You can press the "start" button and as hoped, the UI isn't locked up because the work (the sleep) is done on a background thread but then the UI is updated afterwards, it's important to note that you wouldn't want to stick the update straight after task1 is started in the main code because it would just run immediately.


Comments

Popular posts from this blog

Follow on from home automation post

Functional Filtering in Javascript

Derbyshire Dot Net Talk - Writing Robust Systems