gpt4 book ai didi

c# - 停止并重新启动 HttpListener?

转载 作者:行者123 更新时间:2023-12-03 12:56:08 25 4
gpt4 key购买 nike

我正在开发一个具有 HttpListener 的应用程序。我的目标是让用户根据自己的选择关闭和打开监听器。我将 Listener 放在一个新线程中,但在中止该线程时遇到问题。我在某处读到,如果您尝试中止处于非托管上下文中的线程,那么只要它重新进入托管上下文,就会触发 ThreadAbortException。看起来 HttpListener 的 GetContext() 方法是非托管的,因为当我尝试中止线程时,在我对我的应用程序发出 Web 请求之前什么都没有发生。然后线程退出。问题是当我试图终止线程时,我可能稍后会在同一端口上再次启动该线程,并且 HttpListenerException 消失,表示前缀已注册。

如何终止跨线程的 HttpListener? GetContext() 是否有允许线程中止的托管替代方案?我能否以非托管代码停止的方式中止线程?

最佳答案

比如:

public class XListener
{
HttpListener listener;

public XListener(string prefix)
{
listener = new HttpListener();
listener.Prefixes.Add(prefix);
}

public void StartListen()
{
if (!listener.IsListening)
{
listener.Start();

Task.Factory.StartNew(async () =>
{
while (true) await Listen(listener);
}, TaskCreationOptions.LongRunning);

Console.WriteLine("Listener started");
}
}

public void StopListen()
{
if (listener.IsListening)
{
listener.Stop();
Console.WriteLine("Listener stopped");
}
}

private async Task Listen(HttpListener l)
{
try
{
var ctx = await l.GetContextAsync();

var text = "Hello World";
var buffer = Encoding.UTF8.GetBytes(text);

using (var response = ctx.Response)
{
ctx.Response.ContentLength64 = buffer.Length;
ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
catch (HttpListenerException)
{
Console.WriteLine("screw you guys, I'm going home!");
}
}
}

用法:

var x = new XListener("http://locahost:8080");

x.StartListen();
Thread.Sleep(500); // test purpose only

x.StopListen();
Thread.Sleep(500); // test purpose only

x.StartListen();

/* OUTPUT:
=> Listener started
=> Listener stopped
=> screw you guys, I'm going home!
=> Listener started */

关于c# - 停止并重新启动 HttpListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16946389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com