c# - 发出 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;
}
}
解决方案
很可能会引发未处理的异常,这将导致进程停止。如果您希望服务在出现间歇性问题时继续运行,您需要捕获并记录/处理异常:
void Run() {
while (serviceIsRunning)
{
try {
Image image = Camera.CaptureImage();
CallRestAPI(image);
Thread.Sleep( (int) (1000 / framesPerSecond) );
}
catch (Exception ex)
{
Log.Error(ex);
}
}
}
(对不起格式,我在手机上写这个)
推荐阅读
- xml - XSD 架构:使元素 *List 可选
- r - 如何在 R 中使用 LDAvis 可视化种子 LDA 模型?
- python - 是否可以使用参数自动生成函数?
- ios - Unity-iPhone" 需要配置文件
- javascript - 未显示 svg 内的视频
- java - 无法再运行项目并出现错误:未设置“hibernate.dialect”时对 DialectResolutionInfo 的访问不能为空
- blazor - .Net 5 Blazor WASM 只想在表格列中显示部分字符串
- python - 在python中满足条件后读取下一行的方法
- typescript - 为什么 Typescript 无法找出我的代码中的类型?
- authentication - 命令 ssh-add -K 的“输入身份验证器的 PIN”