C#等待1秒

时间:2011-07-26 18:18:47

标签: c# wpf

是否有像睡眠(秒)这样的功能,但它不会阻止UI更新? 我有一个像这样的代码,如果我在(letters.Children[Words[index].index] as TextBlock).Text = Words[index].LetterCorrect;之后放入线程睡眠(之后我想睡觉)它只等待1秒然后UI得到更新,但我不想要那个。

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 个答案:

答案 0 :(得分:7)

尝试一个计时器并让Elapsed回调执行你想要在一秒钟后发生的代码。

答案 1 :(得分:4)

创建一个工作线程,为您完成工作并让该线程在上班前睡眠所需的时间

e.g。

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

                // do your work here
                // CAUTION: use Invoke where necessary
            });

答案 2 :(得分:1)

将逻辑本身放在与UI线程分开的后台线程中,让该线程等待。

UI线程中等待1秒的任何内容都将锁定整个UI线程。

答案 3 :(得分:1)

使用异步预定回调:

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));
    }
}

答案 4 :(得分:0)

不确定您使用的是哪种框架,但是如果您使用的是Silverlight或WPF,您是否考虑过播放显示正确字母的animation或执行需要1000毫秒的淡入淡出序列?

相关问题