首页 > 解决方案 > 发出 http 请求时的 Windows 服务计时

问题描述

我构建了一个在后台运行很长时间的 Windows 服务,每隔几秒就从网络摄像头拍摄一张照片。

我的问题是在使用 System.Net.Http.HttpClient 将一些图像发布到 REST API 后,Windows 服务停止运行(甚至没有调用 OnStop 方法)。

在几次调用 REST API 后,后台进程暂停。前几个调用工作正常,但随后服务停止运行。

我的代码是这样的:

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

标签: c#.netwindows-services

解决方案


很可能会引发未处理的异常,这将导致进程停止。如果您希望服务在出现间歇性问题时继续运行,您需要捕获并记录/处理异常:

void Run() {
     while (serviceIsRunning)
     {
     try {
         Image image = Camera.CaptureImage();

         CallRestAPI(image);

         Thread.Sleep( (int) (1000 / framesPerSecond) );
     }
     catch (Exception ex)
     {
         Log.Error(ex);
     }
     } 
}

(对不起格式,我在手机上写这个)


推荐阅读