I have worked though the examples on these forums and I don't see an example of my problem. I want to receive a string message, parse it, and then execute a long-running task (1-15 seconds) using a servo. While the long running task is executing, I want to respond to any other requests with a 503.
I coded it like this:
1) Have a global variable
private static bool _servoReady = true;
And then fire up the web server:
private static void SetUpWebServer() { _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipEndpoint = new IPEndPoint(IPAddress.Any, 80); _serverSocket.Bind(ipEndpoint); _serverSocket.Listen(10); ListenForWebRequest(); }
And then handle requests:
public static void ListenForWebRequest() { while (true) { using (Socket clientSocket = _serverSocket.Accept()) { if (_servoReady) { _servoReady = false; String request = GetRequestFromSocket(clientSocket); Thread thread = new Thread(() => HandleWebRequest(request)); thread.Start(); SendActivateResponse(clientSocket); } else { SendBusyResponse(clientSocket); } } } }
In the HandleWebRequest method, I set the _servoReady to true once the servo work is done. The servo work looks like this:
private static void ActivateServoForBellows(String direction, Int32 duration) { if (direction == "UP") { _servo.Duration = SERVO_UP; } else if (direction == "DOWN") { _servo.Duration = SERVO_DOWN; } Thread.Sleep(duration); _servo.Duration = SERVO_NEUTRAL; }
The problem is that this does not work consistently. I make requests and I get several ActivateResponse messages before the 1st ServerBusy messages.
I am wondering is I should lock the _servoReady because I set it to false on the main thread and change it to true on the child tread? Does anyone have any ideas or better yet, a pattern that seems to match my use case?
Thanks in advance.