简体   繁体   English

如何使用 C# 在 UWP 中进行延迟

[英]How to make a delay in a UWP with C#

I'm new on this of C#, I don't know so much of it.我是 C# 的新手,我不太了解。
I'm trying to make an app that changes a TextBlock every second.我正在尝试制作一个每秒更改一个 TextBlock 的应用程序。 The app is UWP and I'm using C#.该应用程序是 UWP,我正在使用 C#。
This is my code:这是我的代码:

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        public bool stop = false;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string input = TextInput.Text + " ";
            TextOutput.Text = input;
            string output = TextOutput.Text;

            for (int i = 0; i <50; i++)
            {
                output = output.Substring(1, output.Length - 1) + output[0];
                TextOutput.Text = output;
                Task.Delay(150);
            }
        }
    }

For now I've tryed Task.Delay() , Thread.Sleep() and others, but this doesn't stop the for-loop.现在我已经尝试过Task.Delay()Thread.Sleep()和其他方法,但这并不能停止 for 循环。
In fact, I've made the same app but for console, and the Thread.Sleep() works perfectly.事实上,我已经为控制台制作了相同的应用程序,并且 Thread.Sleep() 完美运行。
Can you help me, please?你能帮我吗?

You were pretty close, it's just that Task.Delay is a task, perhaps obviously.您非常接近,只是Task.Delay是一项任务,也许很明显。 And you have to await (or continue) tasks:你必须等待(或继续)任务:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        string input = TextInput.Text + " ";
        TextOutput.Text = input;
        string output = TextOutput.Text;

        for (int i = 0; i <50; i++)
        {
            output = output.Substring(1, output.Length - 1) + output[0];
            TextOutput.Text = output;
            await Task.Delay(150);
        }
    }

the value you are passing into Task.Delay / Thread.Sleep is going be milliseconds not seconds.您传递给 Task.Delay / Thread.Sleep 的值将是毫秒而不是秒。

I would try Thread.sleep(1000) // this will you a delay of 1 second.我会尝试 Thread.sleep(1000) // 这会让你延迟 1 秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM