0
    public void OpenUpForm(object sender, EventArgs e)
    {
        if (forms.Count == numberoftimes)
        {
            forms.ForEach(f =>
            {
                f.Close(); 
                f.Dispose(); 
            });
            forms.Clear(); 
            //Need Delay Here
            return;
        }
        forms.Add(new Form1());
        forms.Last().Show();
    }

Hello I have this code, I need to add delay after forms.Clear(); But im new to coding i couldnt figure it out. I have tryed with Task.Delay and Thread.Sleep but it locks my user interface. Is it possible to add a delay that dosent lock the application? Thank you.

C.S.
  • 279
  • 1
  • 6
  • 21
  • I don't understand your need for a delay. This seems like dreadful code. If you run it on a slower computer than yours, does it crash? Blue screen? What if it's faster? – Blindy Nov 01 '15 at 16:48
  • Im adding a numericupdown and want to delay the code for the time selected. Runs ok on slower computers but im open to suggestions. – C.S. Nov 01 '15 at 17:22

1 Answers1

4

You can mark the method async and use this:

await Task.Delay(2000);

will not block the ui thread

public async void OpenUpForm(object sender, EventArgs e)
{
    if (forms.Count == numberoftimes)
    {
        forms.ForEach(f =>
        {
            f.Close(); 
            f.Dispose(); 
        });
        forms.Clear(); 
        await Task.Delay(2000);
        return;
    }
    forms.Add(new Form1());
    forms.Last().Show();
}

This will behave like so.

  • Creates a new task which runs to completion after 2 seconds
  • Ui Thread is bubbled back up to continue executing/processing other events
  • Once the 2 seconds is up UI thread returns and resumes executing the async method from after the await
William
  • 1,837
  • 2
  • 22
  • 36
  • When I debug it I can see the delay timer is set but when I run it it runs like there is no delay (my delay is 7000). – C.S. Nov 01 '15 at 17:37
  • That's because the operation `Task.Delay(7000)` never stales the calling thread. It starts a new thread running and then returns back to where you called it. It then continues executing. The await keyword ensures the code after the Task.Delay will not execute until the 7 seconds are up. – William Nov 01 '15 at 18:12