C#C
C#3y ago
10 replies
Mars

✅ Await seemingly ignored inside Dispatcher.BeginInvoke

I'm writing an app in WPF. Currently testing something out, here's the code I'm testing:

await Dispatcher.BeginInvoke(async () =>
{
    if (!NameTextBox.Text.Equals(oldName))
    {
        NameTextBox.Focusable = false;
        NameTextBox.IsEnabled = false;
                   
        await Task.Delay(1000);
    }
});

_nameUpdateTaskRunning = false;

Dispatcher.Invoke(() =>
{
    NameTextBox.Focusable = true;
    NameTextBox.IsEnabled = true;

    NameCheck.Visibility = Visibility.Visible;
    NameSpinner.Visibility = Visibility.Collapsed;
});


What I want to happen is that the Task.Delay inside the BeginInvoke call will ensure that 1 second passes before the code beginning at _nameUpdateTaskRunning = false starts running. However, when I run this code, the focusable/enabled changes never happen, and the visibility changes happen immediately. I've confirmed by breakpoint debugging that the code block inside the if statement happens.

So I'm guessing that either the focusable/enabled changes aren't being applied, or the awaiting of Task.Delay isn't happening properly and the code keeps running and does the next Dispatcher.Invoke immediately. Does anyone know which it is, and what I can do to fix it?
Was this page helpful?