c# async in wpf code example

Example: c# async in wpf

private async void ButtonClick(object sender, RoutedEventArgs e)
{
    // modify UI object in UI thread
    txt.Text = "started";

    // run a method in another thread
    await HeavyMethod(txt);
    // <>

    // modify UI object in UI thread
    txt.Text = "done";
}

// This is a thread-safe method. You can run it in any thread
internal async Task HeavyMethod(TextBox textBox)
{
    while (stillWorking)
    {
        textBox.Dispatcher.Invoke(() =>
        {
            // UI operation goes inside of Invoke
            textBox.Text += ".";
            // Note that: 
            //    Dispatcher.Invoke() blocks the UI thread anyway
            //    but without it you can't modify UI objects from another thread
        });
        
        // CPU-bound or I/O-bound operation goes outside of Invoke
        // await won't block UI thread, unless it's run in a synchronous context
        await Task.Delay(51);
    }
}

Tags:

Misc Example