Search code examples
c#delay.net-2.0

C# NET. Framework 2.0 | Make a delay?


How can I make my program wait 1 Second and then doing something? Like in NET. Framework 4.8 with Task.Delay() but I'm using NET. Framework 2.0 for a project for my old Windows 2000 Laptop. Is there something I can do?

    panel1.Visible = true;
    //delay
    panel2.Visible = true;
    //delay
    ...

Solution

  • I see you are wanting to make UI panels be visible on a delay. One thing to avoid is any significant delay on the UI thread because your form will be unresponsive during that time and Users may think that it's crashed.

    One good approach is to spawn a worker Thread to perform this delay action without blocking your UI thread. But when it comes time to change the UI panel to Visible it must be marshalled back onto the UI thread using Invoke.

    Here's the code I used to test this answer in C# .Net Framework 2.0. I posted it on GitHub if you'd like to try it.

    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            new Thread(makeVisibleOnDelay).Start();
        }
    
        private void makeVisibleOnDelay()
        {
            Thread.Sleep(1000);
            Invoke((MethodInvoker)delegate { panel1.Visible = true; });
            Thread.Sleep(1000);
            Invoke((MethodInvoker)delegate { panel2.Visible = true; });
        }
    }
    

    Now the panels display progressively:

    Now the panels display progressively