Sign in to follow this  
Errornix

Threading and Sleep() help (C#)

Recommended Posts

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. } } } }

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this