WPF使用计时器重复操作

时间:2015-09-20 23:56:01

标签: c# wpf xaml timer

所以我是WPF的新手,我只是想做一个简单的小程序。当您点击开始按钮时,它将持续打印假代码,直到您点击停止按钮。我试图让它重复,直到停止按钮被击中10种不同的方式,但它们都没有工作。 TextBlock元素将更新一次(或从不),然后整个程序变得不可用并且加载光标出现。我猜这不是经历一个循环,然后更新TextBlocks,而是在后台执行所有操作,而不是直观地更新。

 public partial class MainWindow : Window
{
    System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

    Random r1 = new Random();

    bool stop = false;
    int numUse

    public MainWindow()
    {
        InitializeComponent();


        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        dispatcherTimer.Start();

    }

    //Executes when the start button is hit, begins timer
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        do
        {
            dispatcherTimer.Tick += dispatcherTimer_Tick;
        } while (stop == false);
    }

    //Executes when the stop button is hit, ends timers do while loop
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        stop = true;
    }

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {

            numUse = r1.Next(1, 2);

            if (numUse == 1)
            {
                CodeBlock1.Text = "struct group_info init_groups = { .usage = ATOMIC_INIT(2) }; ";
                CodeBlock2.Text = "";
                CodeBlock3.Text = "struct group_info *groups_alloc(int gidsetsize){ ";
                CodeBlock4.Text = "struct group_info *group_info; ";
                CodeBlock5.Text = "int nblocks; ";
                CodeBlock6.Text = "int i; ";
                CodeBlock7.Text = "";
                CodeBlock8.Text = "initialize stream";
            }
            else if (numUse == 2)
            {
                CodeBlock1.Text = "if (gidsetsize <= NGROUPS_SMALL) ";
                CodeBlock2.Text = "group_info->blocks[0] = group_info->small_block; ";
                CodeBlock3.Text = " else {  ";
                CodeBlock4.Text = " for (i = 0; i < nblocks; i++) { ";
                CodeBlock5.Text = "b = (void *)__get_free_page(GFP_USER);  ";
                CodeBlock6.Text = " goto out_undo_partial_alloc;  ";
                CodeBlock7.Text = "} ";
                CodeBlock8.Text = "";
            } else
            {

            }
    }



}

}

我尝试过循环,同时使用不同的顺序使用不同的方法。我知道我可能在走这些路线时搞砸了,所以任何方法都适合我的目的。显然我在这种情况下使用Timer。

1 个答案:

答案 0 :(得分:4)

没有必要在dispatcherTimer.Tick += dispatcherTimer_Tick的{​​{1}}循环中重复调用while。我怀疑当这个循环运行时,消息泵上没有其他任何东西会运行,包括来自Button_Click的滴答。

您可以取消DispatcherTimer,只需通过从代码中的任何位置调用stop直接对DispatcherTimer采取行动。

也许这样:

Stop()