【发布时间】:2017-12-24 07:45:53
【问题描述】:
我正在创建一个侦听特定 Http 请求的 Windows 服务。我在一个单独的任务中运行httpListener。当服务停止时,我关闭侦听器实例。但似乎 http listenerContext 正在等待传入请求,并且随着侦听器关闭,我收到以下错误
Cannot access a disposed object. Object name: 'System.Net.HttpListener'.
即使我使用某种机制通知StartListening() 监听已停止,它也不会运行,因为相应线程的执行会卡在HttpListenerContext context = await _listener.GetContextAsync(); 直到请求到达。
public void StartListening() {
_listener.Start();
_logger.LogDebug("Http Listening started");
Task.Run(async () => {
while (true) {
try {
if (isOpen == false) {
return 0;
}
HttpListenerContext context = await _listener.GetContextAsync();
HttpListenerRequest request = context.Request;
//processing of the requests url/////
var newUri = request.Url.AbsoluteUri;
_concurrentUrlQueue.Enqueue(newUri);
if (ConcurentUrlQueueChanged != null) ConcurentUrlQueueChanged(this, new EventArgs());
}
catch (Exception e) {
_logger.LogError("Error at get listening context, Message: " + e.Message);
}
}
});
}
public void StopListening() {
isOpen = false;
_logger.LogDebug("Http Listening Stop");
_listener.Close();
}
这是关闭正在侦听以获取上下文的 http 侦听器的适当方法。我使用的代码如下。 谢谢。。
【问题讨论】:
-
谢谢@Ben,我还没有看到这篇文章,它提到使用
BeginGetContext()和EndGetContext(),就像我在以下答案中所做的那样 -
令人惊讶的是,我通过在管理员模式下运行我的 IDE 解决了这个问题。我讨厌 Windows
标签: c# .net asynchronous httplistener