0

This program show two card deck. I want to move on card (picturbox14) to the other card deck(440,50) and then, after 2 seconds i want to place it behinde the other card deck. When I dont have a delay (thread.sleep) the card moves just fine but of course it goes directly to the back of the other deck. But when i have a timer the card is shown above boths deck first and then after 2 seconds it goes to the back like it should. How do i change it's position then wait and then let it go to the back of the deck without it to show on both decks first?

void PictureBox2Click(object sender, EventArgs e)
        {

            pictureBox14.Location= new Point(440,50);
            pictureBox2.BackgroundImage = olikakort[färg];
            System.Threading.Thread.Sleep(2000);
            pictureBox14.SendToBack();

        }
Anton Las
  • 27
  • 6
  • 1
    Mark method `async` and do `await Task.Delay(2000);` instead of sleeping. – Sinatr May 13 '20 at 08:55
  • 1
    Does this answer your question? [Wait for a while without blocking main thread](https://stackoverflow.com/questions/8496275/wait-for-a-while-without-blocking-main-thread) – Sinatr May 13 '20 at 08:55
  • 1
    `private async void PictureBox2Click(...) { ... await Task.Delay(2000); pictureBox14.SendToBack(); }` (`Thread.Sleep()` blocks the UI Thread, it can do nothing in the meanwhile. Making the event handler async and awaiting `Task.Delay()`, lets the UI Thread continue its operations. Which also allows you to click the PictureBox again, raising a new event, so maybe disable it and then enable it again when `Task.Delay()` returns). – Jimi May 13 '20 at 08:56
  • 1
    I mean, disable the event handler, not the Control (otherwise you'll see a grayed-out image). – Jimi May 13 '20 at 09:02
  • @Jimi I tried to impliment the `async` and `task.Delay()` like this `private async void PictureBox2Click(object sender, EventArgs e)` and then `await Task.Delay(2000);`but it doesn't recognize `Task.Delay()`what am I doing wrong?(I'm new to programing so could be something for others obvious) (thank you for the answer!) – Anton Las May 13 '20 at 16:49
  • 1
    Do you have `using System.Threading.Tasks` on top of your class? Are you using a .Net Framework version >= 4.5? – Jimi May 13 '20 at 16:58
  • @Jimi yup that was the problem. Thank you so much! – Anton Las May 13 '20 at 17:34

0 Answers0