📜  c# async in wpf - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:50.230000             🧑  作者: Mango

代码示例1
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);
    }
}