如何在C#Windows窗体应用程序中创建无限循环

时间:2016-11-16 20:47:18

标签: c# windows forms

我编写了一个C#程序,它应该循环代码以刷新DateTime信息并设置标签的文本以匹配。但是,当我运行它时,表单不会显示。为什么会发生这种情况,如何显示表单?

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

    namespace Clock
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new clock());
            }
        }
    }

忽略我的缩进(可能是也可能不对,但在程序中是正确的),我做错了什么,我该如何解决?

谢谢!

Logan Slowik

1 个答案:

答案 0 :(得分:2)

好像你用无限循环来阻止UI线程。您可以使用async来避免阻止您的UI ...只需在Form_Load方法中调用此方法即可。 InfiniteLoop();

async void InfiniteLoop()
{
    while(true)
    {
        await Task.Delay(100);
        this.Text = DateTime.Now.ToString();
    }
}

您也可以考虑使用Timer