2
2
{
3
3
using System ;
4
4
using System . Net ;
5
+ using System . Security ;
5
6
using System . Threading ;
6
7
7
8
public class SimpleServer : IDisposable
8
9
{
9
10
private readonly HttpListener listener ;
10
11
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
+ }
12
19
13
20
public static SimpleServer Create (
14
21
string url ,
@@ -22,12 +29,6 @@ public static SimpleServer Create(
22
29
return server ;
23
30
}
24
31
25
- private SimpleServer ( HttpListener listener , Action < HttpListenerContext > handler )
26
- {
27
- this . listener = listener ;
28
- this . handler = handler ;
29
- }
30
-
31
32
public void Start ( )
32
33
{
33
34
if ( this . listener . IsListening )
@@ -37,20 +38,43 @@ public void Start()
37
38
38
39
this . listener . Start ( ) ;
39
40
40
- this . processor = new Thread ( ( ) =>
41
+ this . thread = new Thread ( ( ) =>
41
42
{
42
43
var context = this . listener . GetContext ( ) ;
43
44
this . handler ( context ) ;
44
45
context . Response . Close ( ) ;
45
46
} ) { Name = "WebServer" } ;
46
47
47
- this . processor . Start ( ) ;
48
+ this . thread . Start ( ) ;
48
49
}
49
50
50
51
public void Dispose ( )
51
52
{
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
+
54
78
this . listener . Close ( ) ;
55
79
}
56
80
}
0 commit comments