JD
John Doe

Posted: 2023-10-27 10:15 AM

Problem with Task.Run and UI Updates

Hello everyone,

I'm working on a C# WPF application and I'm facing an issue with updating the UI after performing a long-running operation using Task.Run. I understand that I should use Dispatcher.Invoke or the await keyword to marshal UI updates back to the UI thread, but I'm struggling to implement it correctly.

Here's a simplified version of my code:


public async void FetchDataButton_Click(object sender, RoutedEventArgs e)
{
    var progress = new Progress(data =>
    {
        // This is where the UI update is supposed to happen
        OutputTextBox.AppendText(data + Environment.NewLine);
    });

    await Task.Run(() => DoLongOperation(progress));
}

private void DoLongOperation(IProgress progress)
{
    for (int i = 0; i < 10; i++)
    {
        Thread.Sleep(500); // Simulate work
        string message = $"Processing item {i + 1}...";
        progress.Report(message); // Report progress
    }
    progress.Report("Operation completed!");
}
            

When I run this, the OutputTextBox doesn't update immediately, and sometimes it freezes momentarily. Am I missing something in how Progress<T> interacts with the UI thread?

Any guidance would be greatly appreciated!