Reputation: 13
I built a Windows Service that runs in the background for a long period of time taking a photo from the webcam every few seconds.
My problem is the windows service stops running (without even calling the OnStop method) after posting a few images to a REST API using the System.Net.Http.HttpClient.
The background process suspends after a few calls to the REST API. The first few calls work fine, but then the service stops running.
My code is something like this:
protected override void OnStart(string[] args)
{
serviceIsRunning = true;
thread = new Thread(Run);
thread.Start();
}
void Run() {
while (serviceIsRunning)
{
Image image = Camera.CaptureImage();
CallRestAPI(image);
Thread.Sleep( (int) (1000 / framesPerSecond) );
}
}
HttpClient client = null;
void CallRestAPI(Image image)
{
if (client == null)
{
client = new HttpClient();
client.DefaultRequestHeaders.Add("...", "...");
}
string requestParameters = "...";
string uri = uriBase + "?" + requestParameters;
// Request body. Posts a JPEG image.
using (ByteArrayContent content = new ByteArrayContent(ImageToByteArray(image)))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// Execute the REST API call.
HttpResponseMessage response = client.PostAsync(uri, content).Result;
// Get the JSON response.
string contentString = response.Content.ReadAsStringAsync().Result;
}
}
Upvotes: 1
Views: 544
Reputation: 7111
It probably crashed. Have you looked in the event log? Do you do any logging in your code (to somewhere)?
Once you get this debugged, consider configuring your service to restart after a crash (but making sure not get into a crash, restart, repeat loop) by configuring "recovery" options for the service.
Note that your description says "taking a photo from the webcam every few seconds", but your code says: Thread.Sleep( (int) (1000 / framesPerSecond) );
Upvotes: 1
Reputation: 86779
Most likely there is an unhandled exception being thrown, which will cause the process to stop. If you want the service to continue running when there are intermittent problems you need to catch and log / handle the exception:
void Run() {
while (serviceIsRunning)
{
try {
Image image = Camera.CaptureImage();
CallRestAPI(image);
Thread.Sleep( (int) (1000 / framesPerSecond) );
}
catch (Exception ex)
{
Log.Error(ex);
}
}
}
(sorry about the formatting, I'm writing this on a phone)
Upvotes: 1