强制WPF UI线程更新任务

时间:2019-01-14 06:51:12

标签: c# wpf multithreading task system.timers.timer

当前此代码有效,我想它不能按预期工作,因为我还没有弄清楚如何为按钮中的每个不透明度更改强制更新UI线程。

    private void BtnStart_Click(object sender, RoutedEventArgs e) {
        // Create a timer and add its corresponding event

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += TimerFade_Elapsed;

        timer.Interval = 750;

        // Want a new thread to run this task on so
        // the main thread doesn't wait.

        Task task = new Task(() => timer.Start());
        task.Start();          
        //r.SingleThread();

    }

    private void TimerFade_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
        // Access UI thread to decrease Opacity on a button from a different thread.

        Dispatcher.Invoke(() => {
            if (btnStart.Opacity != 0.0) {
                btnStart.Opacity -= 1.0;
                // code here to force update the GUI.
            } else {
                System.Timers.Timer t;
                t = (System.Timers.Timer)sender;
                t.Stop();
            }
        });          

    }

该代码无论从外观上还是在外观上都没有。我怀疑这与我在进行更改时不更新GUI有关。

2 个答案:

答案 0 :(得分:0)

提供的代码运行正常。不透明度的值范围为0到1。您在第一次设置时将其设置为1,这会使按钮在第一次刷新时消失。如果您可以更改以下行

  

btnStart.Opacity-= 1.0;

收件人

  

btnStart.Opacity-= 0.1;

您将能够看到按钮逐渐褪色。

PS:最好的方法是使用@zack提到的StoryBoard(DoubleAnimation)

答案 1 :(得分:0)

您可以简单地使用情节提要。在对象的资源中创建一个(例如int i; for (i = 2; i*i <= n; i++) { if (n % i == 0) { /* p(); */ break; } } if(i*i > n) notp(); else p(); / Window或其他任何东西),然后从后面的代码中调用情节提要。

这是一个示例:

Page

然后从后面的代码中调用它:

 <Window.Resources>
 <Storyboard x:Key="FadeAnim">
        <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.4"/>
    </Storyboard>
 </Window.Resources>
相关问题