3

Is there such a function like sleep(seconds) but it wouldn't block UI updates? I have a code like this and if I put threading sleep after (letters.Children[Words[index].index] as TextBlock).Text = Words[index].LetterCorrect; (I want to sleep after that) it just waits 1 sec and then UI gets updates, but I dont want that.

private void Grid_Click(object sender, RoutedEventArgs e)
{
    if (index == Words.Count() - 1) return;
    if ((((e.Source as Button).Content as Viewbox).Child as Label).Content.ToString() == Words[index].LetterCorrect)
    {
        (letters.Children[Words[index].index] as TextBlock).Text = Words[index].LetterCorrect;

        letters.Children.Clear();
        LoadWord(++index);
        this.DataContext = Words[index];
    }
}

5 Answers5

7

Try a Timer and have the Elapsed callback execute the code you want to happen after the one second.

Ryan Bennett
  • 3,404
  • 19
  • 32
5

Create a working thread that does the work for you and let that thread sleep for the desired time before going to work

e.g.

ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(1000);

                // do your work here
                // CAUTION: use Invoke where necessary
            });
yas4891
  • 4,774
  • 3
  • 34
  • 55
1

Put the logic itself in a background thread separate from the UI thread and have that thread wait.

Anything in the UI thread that waits 1 second will lock up the entire UI thread for that second.

1

Use an async scheduled callback:

private void Grid_Click(object sender, RoutedEventArgs e)
{
    if (index == Words.Count() - 1) return;
    if ((((e.Source as Button).Content as Viewbox).Child as Label).Content.ToString() == Words[index].LetterCorrect)
    {
        (letters.Children[Words[index].index] as TextBlock).Text = Words[index].LetterCorrect;

        Scheduler.ThreadPool.Schedule(schedule =>
        {
           letters.Children.Clear();
           LoadWord(++index);
           this.DataContext = Words[index];

        }, TimeSpan.FromSeconds(1));
    }
}
Jonathan Holland
  • 1,243
  • 11
  • 17
0

Not sure what framework you are using, but if you are using Silverlight or WPF, have you considered playing an animation that reveals the correct letter or does a fade sequence that takes 1000ms?

Bobby D
  • 2,129
  • 14
  • 21