-2

I have been wondering how to make a delay. I have tried thread.sleep but it stops the project. I would want to do something like:

Form4 ss = new Form4();
ss.Show();
wait(4000) //4000 miliseconds
ss.close();

I tried await Task.Delay(4000); but it said: I had the wrong return type Please help

AA AA
  • 5
  • 3
  • 1
    `Thread.Sleep(4000);` – Jahed Kabiri Dec 13 '17 at 23:40
  • 3
    I assume you are using WinForms. Thread.Sleep will stop your UI thread. Use `await Task.Delay(4000);` instead. – Ilian Dec 13 '17 at 23:45
  • Is it winforms or what? Let me assume yes! Thread.Sleep(4000) blocks the messages on current thread so your window have no time to show itself. Instead do this: Task.Delay(4000) .ContinueWith(t=>form.Close(), TaskScheduler.FromCurrentSynchronizationContext()); – Arek Bal Dec 13 '17 at 23:49
  • You seriously could not find any snippet anywhere showing how to do a delay?? The first google hit for your title: https://stackoverflow.com/q/5449956/1070452 – Ňɏssa Pøngjǣrdenlarp Dec 14 '17 at 01:02

3 Answers3

1

You can use Task.Delay():

Form4 ss = new Form4();
ss.Show();
await Task.Delay(4000);
ss.Close();
adjan
  • 13,371
  • 2
  • 31
  • 48
  • When I try await Task.Delay(4000) it gives me this problem: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. – AA AA Dec 13 '17 at 23:50
  • 1
    the error tells you what the problem means @AAAA come on man.. decorate your method with `async` start using Google please – MethodMan Dec 13 '17 at 23:51
  • Sorry lol, I did that and it gave me this error: https://gyazo.com/b182a01a27ce0980bf1c769e97bf4013 – AA AA Dec 14 '17 at 00:03
1

decorate your method like this

public async Task MyWaitMethod() 
{
    await Task.Run(async () => //Task.Run automatically unwraps nested Task types!
    {
        Console.WriteLine("Start");
        await Task.Delay(5000);
        Console.WriteLine("Done");
    });
    Console.WriteLine("All done");
}

if you do not understand the first example use a simple straight forward one like this

public async Task MyWaitMethod() 
{
    await Task.Delay(5000);
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • thanks but its saying it has the wrong return type. Heres a pic: https://gyazo.com/b182a01a27ce0980bf1c769e97bf4013 – AA AA Dec 14 '17 at 00:08
  • @AA if the return type is important you should have included it in your question. And [don't post pictures of errors](http://idownvotedbecau.se/imageofanexception/). – Dour High Arch Dec 14 '17 at 00:50
  • It is in the question – AA AA Dec 14 '17 at 00:52
0

Use a timer?

Create a timer with 4000 interval and set its tick event to close the form. replace your wait(4000) with Timer start event. Make sure to also stop the timer after closing your form.

crimson589
  • 1,238
  • 1
  • 20
  • 36