22{
33 using System ;
44 using System . Net ;
5+ using System . Security ;
56 using System . Threading ;
67
78 public class SimpleServer : IDisposable
89 {
910 private readonly HttpListener listener ;
1011 private readonly Action < HttpListenerContext > handler ;
11- private Thread processor ;
12+ private Thread thread ;
13+
14+ private SimpleServer ( HttpListener listener , Action < HttpListenerContext > handler )
15+ {
16+ this . listener = listener ;
17+ this . handler = handler ;
18+ }
1219
1320 public static SimpleServer Create (
1421 string url ,
@@ -22,12 +29,6 @@ public static SimpleServer Create(
2229 return server ;
2330 }
2431
25- private SimpleServer ( HttpListener listener , Action < HttpListenerContext > handler )
26- {
27- this . listener = listener ;
28- this . handler = handler ;
29- }
30-
3132 public void Start ( )
3233 {
3334 if ( this . listener . IsListening )
@@ -37,20 +38,43 @@ public void Start()
3738
3839 this . listener . Start ( ) ;
3940
40- this . processor = new Thread ( ( ) =>
41+ this . thread = new Thread ( ( ) =>
4142 {
4243 var context = this . listener . GetContext ( ) ;
4344 this . handler ( context ) ;
4445 context . Response . Close ( ) ;
4546 } ) { Name = "WebServer" } ;
4647
47- this . processor . Start ( ) ;
48+ this . thread . Start ( ) ;
4849 }
4950
5051 public void Dispose ( )
5152 {
52- this . processor . Abort ( ) ;
53- this . listener . Stop ( ) ;
53+ try
54+ {
55+ this . thread . Abort ( ) ;
56+ }
57+ catch ( ThreadStateException threadStateException )
58+ {
59+ Console . WriteLine ( "Issue aborting thread - {0}." , threadStateException . Message ) ;
60+ }
61+ catch ( SecurityException securityException )
62+ {
63+ Console . WriteLine ( "Issue aborting thread - {0}." , securityException . Message ) ;
64+ }
65+
66+ if ( this . listener . IsListening )
67+ {
68+ try
69+ {
70+ this . listener . Stop ( ) ;
71+ }
72+ catch ( ObjectDisposedException objectDisposedException )
73+ {
74+ Console . WriteLine ( "Issue stopping listener - {0}" , objectDisposedException . Message ) ;
75+ }
76+ }
77+
5478 this . listener . Close ( ) ;
5579 }
5680 }
0 commit comments