Perform work in response to a button click and update the UI

suggest change

This example responds to a button click by doing work on a worker thread, then updates the user interface when that work finishes. Call it from the UI thread so TaskScheduler.FromCurrentSynchronizationContext can capture the UI scheduler.

void MyButton_OnClick(object sender, EventArgs args)
{
    Task.Run(() => // Schedule work using the thread pool
        {
            System.Threading.Thread.Sleep(5000); // Sleep for 5 seconds to simulate work.
        })
    .ContinueWith(p => // this continuation contains the 'update' code to run on the UI thread
    {
        this.TextBlock_ResultText.Text = "The work completed at " + DateTime.Now.ToString();
    },
    TaskScheduler.FromCurrentSynchronizationContext()); // make sure the update is run on the UI thread.

}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents