-1

I'm trying to emulate a process where buttons are sequentially getting set to one colour then back to their previous colour every few seconds.

Problem is, I am not entirely sure how to iterate through a collection without blocking the UI thread... i don't like using thread.sleep but this is what i found on SO.

Anyone aid me? Posting code I have below for Start button click

    private void StartTest_Click(object sender, RoutedEventArgs e)
    {
        //tabControl.SelectedIndex = 3;
        // Emulate buttons being processed
        Dispatcher.Invoke(() =>
        {
            new Task(() =>
            {
                selectedButtons.All(bSelected=>
                {
                    bSelected.Background = resourceDictionary["ProcessingButtonColour"] as Brush;
                    Thread.Sleep(3000);
                    bSelected.Background = resourceDictionary["HoverOverColourInactive"] as Brush;
                    return true;
                });
            }).Start();
        });
    }
slickchick2
  • 137
  • 9

1 Answers1

1

You shouldn't need Dispatcher.Invoke here if your button is clicked from the UI then your on the UI thread. Just loop through the buttons and change their color. No reason to Select just to return a dummy true value. Also, no reason hardly ever to use a Task constructor, especially not to run work back on the UI thread. Something like this should work:

private async void StartTest_Click(object sender, RoutedEventArgs e)
{
    foreach (var button in selectedButtons)
    {
        button.Background = resourceDictionary["ProcessingButtonColour"] as Brush;
        await Task.Delay(3000);
        button.Background = resourceDictionary["HoverOverColourInactive"] as Brush;
    }
}
JSteward
  • 6,833
  • 2
  • 21
  • 30
  • Awesome - thanks man.... So was my understanding just wrong? I need to read up more about async and await... I can never fully remember threading "functions" – slickchick2 Aug 08 '19 at 22:09
  • also, really quickly, how would I be able to disable the button whilst these tasks are happening? Guess that would change the logic a bit.. – slickchick2 Aug 08 '19 at 22:11
  • You mean while the color is changing? It's just matter of where you put `button.Enabled = false` / `button.Enabled = true` – JSteward Aug 08 '19 at 22:14
  • not the actual button that's changing but the button that triggered it all off, i.e. in the example "StartTest". How would we disable that main button until it's all finished? Sorry to ask another question... – slickchick2 Aug 08 '19 at 22:15
  • 1
    Oh, just use `StartTest.Enabled = false` before the `foreach` and `StartTest.Enabled = true` after the `foreach` – JSteward Aug 08 '19 at 22:18
  • Awesome... really appreciate it man :) – slickchick2 Aug 08 '19 at 22:21