Logan Slowik Logan Slowik - 19 days ago 6
C# Question

How do I make an infinite loop in C# Windows Form Application

I have written a C# program that should loop the code to refresh the DateTime info and set the text of a label to match. However, when I run it, the form doesn't display. Why does this happen, and how do I make the form be shown?

This is my code:

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


Ignoring my indentions (which may or may not be right, but are correct in the program), what am I doing wrong, and how do I fix it?

Thanks!

Logan Slowik

L.B L.B
Answer

Seems like you are blocking the UI thread with your infinite loop. You can utilize async to avoid blocking your UI... Just call this method in your Form_Load method. InfiniteLoop();

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

You may also consider using Timer

Comments