kenetik
kenetik

Reputation: 350

C# Waiting on a boolean

I have some code in which I am waiting on the current x,y,z position of a motor to be equal to the position I sent to the motors. There is no command to ask the motors directly so I set up a boolean to be set to true when the current.x , current.y, and current.z are equal to my move(x,y,z) numbers.

I have tried several different ideas, first, setting up a timer and on each tick of the timer, check if the values are equal. But with this attempt I can't get the code to wait if they are not equal.

I also tried a recursion method where if the boolean was false, wait some milliseconds and check again. The code said I had infinite recursion and returned a stackoverflow.

How can I wait for the motors to stop moving before sending my next command?

(The only data I can access from the motor is the current position of it)

Upvotes: 0

Views: 3218

Answers (4)

Pawan Mishra
Pawan Mishra

Reputation: 7268

You can create an event and register the waiting code with the event. Back in the motors code, as soon as the values matches, you can fire the event.

Upvotes: 2

JaredPar
JaredPar

Reputation: 754575

If you have communication between 2 threads where one is waiting for the other to reach a certain condition then the easiest mechanism is to use a WaitHandle of sort. In this case I would recommend an AutoResetEvent.

// Shared
AutoResetEvent m_moveHit = new AutoResetEvent(false);

// Thread 1 
void MoveHit(Position position) {
  if (position == thePositionDesired) {
    m_moveHit.Set();
  }
}

// Thread 2
void Go() {
  // Wait until the move happens 
  m_moveHit.WaitOne();

  // Won't get here until it happens
}

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283614

If you convert recursion into iteration (a while loop), you won't get a stack overflow.

Upvotes: 1

AD.Net
AD.Net

Reputation: 13399

You could possibly try to have some sort of event triggered when all the values are equal to the values you want and have your actor class subscribe to the event.

Upvotes: 1

Related Questions