[英]Windows Service timing while making http requests
我構建了一個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;
}
}
最有可能引發了未處理的異常,這將導致進程停止。 如果您希望服務在出現間歇性問題時繼續運行,則需要捕獲並記錄/處理異常:
void Run() {
while (serviceIsRunning)
{
try {
Image image = Camera.CaptureImage();
CallRestAPI(image);
Thread.Sleep( (int) (1000 / framesPerSecond) );
}
catch (Exception ex)
{
Log.Error(ex);
}
}
}
(對不起格式,我是在手機上寫的)
它可能崩潰了。 您是否查看了事件日志? 您是否在代碼中進行任何登錄(到某處)?
調試完成后,請考慮通過配置服務的“恢復”選項 ,將服務配置為在崩潰后重新啟動(但請確保不會崩潰,重新啟動,重復循環)。
請注意,您的描述為“每隔幾秒鍾從網絡攝像頭拍攝一張照片”,但是您的代碼顯示為: Thread.Sleep( (int) (1000 / framesPerSecond) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.