6
6
using System . IO ;
7
7
using System . Threading ;
8
8
using System . Threading . Tasks ;
9
+ using System . Net . Sockets ;
9
10
10
11
namespace Microsoft . Data . SqlClient . SNI
11
12
{
@@ -30,7 +31,49 @@ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Cancel
30
31
try
31
32
{
32
33
return _readAsyncQueueSemaphore . WaitAsync ( )
33
- . ContinueWith < int > ( _ => base . ReadAsync ( buffer , offset , count , cancellationToken ) . GetAwaiter ( ) . GetResult ( ) ) ;
34
+ . ContinueWith ( _ => base . ReadAsync ( buffer , offset , count , cancellationToken ) . GetAwaiter ( ) . GetResult ( ) ) ;
35
+ }
36
+ finally
37
+ {
38
+ _readAsyncQueueSemaphore . Release ( ) ;
39
+ }
40
+ }
41
+
42
+ // Prevent the WriteAsync's collision by running task in Semaphore Slim
43
+ public override Task WriteAsync ( byte [ ] buffer , int offset , int count , CancellationToken cancellationToken )
44
+ {
45
+ try
46
+ {
47
+ return _writeAsyncQueueSemaphore . WaitAsync ( ) . ContinueWith ( _ => base . WriteAsync ( buffer , offset , count , cancellationToken ) ) ;
48
+ }
49
+ finally
50
+ {
51
+ _writeAsyncQueueSemaphore . Release ( ) ;
52
+ }
53
+ }
54
+ }
55
+
56
+ /// <summary>
57
+ /// This class extends NetworkStream to customize stream behavior for Managed SNI implementation.
58
+ /// </summary>
59
+ internal class SNINetworkStream : NetworkStream
60
+ {
61
+ private readonly ConcurrentQueueSemaphore _writeAsyncQueueSemaphore ;
62
+ private readonly ConcurrentQueueSemaphore _readAsyncQueueSemaphore ;
63
+
64
+ public SNINetworkStream ( Socket socket , bool ownsSocket ) : base ( socket , ownsSocket )
65
+ {
66
+ _writeAsyncQueueSemaphore = new ConcurrentQueueSemaphore ( 1 ) ;
67
+ _readAsyncQueueSemaphore = new ConcurrentQueueSemaphore ( 1 ) ;
68
+ }
69
+
70
+ // Prevent the ReadAsync's collision by running task in Semaphore Slim
71
+ public override Task < int > ReadAsync ( byte [ ] buffer , int offset , int count , CancellationToken cancellationToken )
72
+ {
73
+ try
74
+ {
75
+ return _readAsyncQueueSemaphore . WaitAsync ( )
76
+ . ContinueWith ( _ => base . ReadAsync ( buffer , offset , count , cancellationToken ) . GetAwaiter ( ) . GetResult ( ) ) ;
34
77
}
35
78
finally
36
79
{
0 commit comments