Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created August 15, 2014 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DominicFinn/dfd4dae0e93ff2072c10 to your computer and use it in GitHub Desktop.
Save DominicFinn/dfd4dae0e93ff2072c10 to your computer and use it in GitHub Desktop.
Accessing the UI Thread in the right context in tasks
open System.Windows.Forms
open System.Threading.Tasks
let createForm() =
let form = new Form()
let button = new Button()
button.Text <- "Start"
form.Controls.Add(button)
form
let createLabel() =
let label = new Label()
label.Location <- new System.Drawing.Point(55, 109); // aka anywhere out of the way
label.Text <- "Ready?"
label.Name <- "Status"
label
let form = createForm()
let label = createLabel()
form.Controls.Add(label)
let sleepTask() =
System.Threading.Thread.Sleep(5000)
let updateFormTask(previousTask) =
// this is now in the right context
label.Text <- "done"
()
let task1 = Task.Factory.StartNew(sleepTask)
let task2 = task1.ContinueWith(updateFormTask, TaskScheduler.FromCurrentSynchronizationContext())
form.Show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment