Search code examples
c#wpfmultithreadingtextblock

TextBlock Will Not Update


I have a text block called "findListText". Here, I am updating the text in it:

private void InstantSearch(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        HitEnter = true;
    }
    findListText.Text = "Processing request. Please wait...";
    Find(bool.Parse("False" as string));
}

However, the next set of code is a search function that can take up to 10 seconds, and at the end of it, it changes the text in findListText again.

private void Find(bool? bForward = true)
{
    {
        //Lots and lots of code
    }
    findListText.Text = "Search completed."
}

The problem is, the textblock never seems to update to "Processing request. Please wait...". The textblock is in it's original state and 10 seconds later updates to "Search completed.", seemingly skipping out the middle man.

I'm using C# - WPF. What am I doing wrong here?


Solution

  • Doesn't matter what technology I think.

    The code is running on the same thread, meaning the the UI won't be updated untill all the code on that thread is completed. You should address a different thread to update that textblock.

    In that case, you will have 2 thread:

    • The origininal thread, executing the "lots and lots of code"
    • The second (extra) created thread, which will handle updating the textblock's text while the other thread is executing the other code.

    I've created a little something that should resolve your problem, it's based on this Stack Overflow page