Tôi đang sử dụng một HttpListener và sử dụng BeginGetContext để có được đối tượng bối cảnh của tôi. Tôi muốn xóa sạch HttpListener của mình nhưng nếu tôi cố gắng thực hiện một Close trên trình nghe, tôi nhận được ngoại lệ và nó khiến chương trình của tôi thoát.Làm sạch interupt HttpListener của BeginGetContext phương pháp
using System;
using System.Net;
namespace Sandbox_Console
{
class Program
{
public static void Main()
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// Create a listener.
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://vwdev.vw.local:8081/BitsTest/");
listener.Start();
Console.WriteLine("Listening...");
listener.BeginGetContext(Context, listener);
Console.ReadLine();
listener.Close(); //Exception on this line, but not shown in Visual Studio
Console.WriteLine("Stopped Listening..."); //This line is never reached.
Console.ReadLine();
}
static void Context(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
context.Response.Close();
listener.BeginGetContext(Context, listener);
}
}
}
Chương trình ném một ngoại lệ trên listener.Close()
tuy nhiên lỗi không bao giờ được thể hiện trong Visual Studio, các lưu ý duy nhất tôi nhận được là những điều sau đây trong màn hình đầu ra gỡ lỗi:
Một cơ hội ngoại lệ đầu tiên của loại 'System.ObjectDisposedException' xảy ra trong System.dll
Chương trình '[2568] Sandbox Console.vshost.exe: Quản lý (v4.0.30319)' đã thoát với mã 0 (0x0).
tôi đã có thể để có được những execption thực từ cửa sổ Event Viewer
Application: Sandbox Console.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ObjectDisposedException Stack: at System.Net.HttpListener.EndGetContext(System.IAsyncResult) at Sandbox_Console.Program.Context(System.IAsyncResult) at System.Net.LazyAsyncResult.Complete(IntPtr) at System.Net.ListenerAsyncResult.WaitCallback(UInt32, UInt32, System.Threading.NativeOverlapped*) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
sao tôi cần phải làm gì để tôi có thể đóng HttpListener sạch của tôi?
Vì vậy, async của bạn 'khoảng trống tĩnh Bối cảnh' không bao giờ được gọi? .. một cái gì đó đã đi awry .. 'ObjectDisposedException' được ném khi bạn cố gắng xử lý một đối tượng đã được xử lý. Một cái gì đó cho tôi biết sự khởi tạo của người nghe của bạn bị hỏng. –
@SimonWhitehead AH AH! Bối cảnh được gọi là lần cuối khi bạn gọi Đóng. Viết một giải pháp. –