Threading and Sleep() help (C#)

Started by
4 comments, last by Arild Fines 19 years, 5 months ago
I'm having some trouble getting Sleep() to work in my chess program. In one of my loops, I want it to sleep for 1 second each time it goes through. But, what's happening is it sleeps the first time through and then after that it runs through the loop as if the Sleep() method isn't even there. Here is a part of the code: private void Begin_Click(object sender, System.EventArgs e) { char [,] board = new char[N,N]; placeQueen(board, 0,); int x; int y; for(x = 1; x <= N; x++) { for(y = 1; y <= N; y++) { if(board[x-1,y-1] == 'Q') { Thread.Sleep(1000); //Do more things here. } } } }
Advertisement
the sleep function only gets called if:

if(board[x-1,y-1] == 'Q')
{
Thread.Sleep(1000);
}

The position on the board is not equal to 'Q' so sleep is not called.

Move the Thread.Sleep() outside of the if-statement if you want it to be called every time.
This would have been a great time to use your visual debugger and step through the code. I rarely used my debugger in c++ when I was making text based things, but when I started programming C# I just gave it a try and it works damn well to find logical mistakes. Remember this next time.
Dat is off da hizzle fo shizzle dizzle
Well the program runs through the for loops very quickly so it only seems to sleep when its actually doing something. When I put Sleep out side of the if statement my program freezes.
Can you give some more background info on what it is you're trying to do with the sleeps?

From this code all i can get is that you want to pause the game for 1 second when it finds a Queen on the board. What is the purpose of the sleep?

If you want to pause the game for 1 second each time it goes through the loop, your going to get a 64 second sleep.
You should never have a Sleep() in a Windows Forms event handler. While you are sleeping, the windows message pump won't run, and your form will look as if it is hung.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

This topic is closed to new replies.

Advertisement