1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
|
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient
{
sealed internal class SqlSequentialStream : System.IO.Stream
{
private SqlDataReader _reader; // The SqlDataReader that we are reading data from
private int _columnIndex; // The index of out column in the table
private Task _currentTask; // Holds the current task being processed
private int _readTimeout; // Read timeout for this stream in ms (for Stream.ReadTimeout)
private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal
internal SqlSequentialStream(SqlDataReader reader, int columnIndex)
{
Debug.Assert(reader != null, "Null reader when creating sequential stream");
Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential stream");
_reader = reader;
_columnIndex = columnIndex;
_currentTask = null;
_disposalTokenSource = new CancellationTokenSource();
// Safely safely convert the CommandTimeout from seconds to milliseconds
if ((reader.Command != null) && (reader.Command.CommandTimeout != 0))
{
_readTimeout = (int)Math.Min((long)reader.Command.CommandTimeout * 1000L, (long)Int32.MaxValue);
}
else
{
_readTimeout = Timeout.Infinite;
}
}
public override bool CanRead
{
get { return ((_reader != null) && (!_reader.IsClosed)); }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanTimeout
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{ }
public override long Length
{
get { throw ADP.NotSupported(); }
}
public override long Position
{
get { throw ADP.NotSupported(); }
set { throw ADP.NotSupported(); }
}
public override int ReadTimeout
{
get { return _readTimeout; }
set
{
if ((value > 0) || (value == Timeout.Infinite))
{
_readTimeout = value;
}
else
{
throw ADP.ArgumentOutOfRange("value");
}
}
}
internal int ColumnIndex
{
get { return _columnIndex; }
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateReadParameters(buffer, offset, count);
if (!CanRead)
{
throw ADP.ObjectDisposed(this);
}
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
try
{
return _reader.GetBytesInternalSequential(_columnIndex, buffer, offset, count, _readTimeout);
}
catch (SqlException ex)
{
// Stream.Read() can't throw a SqlException - so wrap it in an IOException
throw ADP.ErrorReadingFromStream(ex);
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (!CanRead)
{
// This is checked in ReadAsync - but its a better for the user if it throw here instead of having to wait for EndRead
throw ADP.ObjectDisposed(this);
}
Task readTask = ReadAsync(buffer, offset, count, CancellationToken.None);
if (callback != null)
{
readTask.ContinueWith((t) => callback(t), TaskScheduler.Default);
}
return readTask;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw ADP.ArgumentNull("asyncResult");
}
// Wait for the task to complete - this will also cause any exceptions to be thrown
Task<int> readTask = (Task<int>)asyncResult;
try
{
readTask.Wait();
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
return readTask.Result;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateReadParameters(buffer, offset, count);
TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
if (!CanRead)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
try
{
Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
if (original != null)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
}
else
{
// Set up a combined cancellation token for both the user's and our disposal tokens
CancellationTokenSource combinedTokenSource;
if (!cancellationToken.CanBeCanceled)
{
// Users token is not cancellable - just use ours
combinedTokenSource = _disposalTokenSource;
}
else
{
// Setup registrations from user and disposal token to cancel the combined token
combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposalTokenSource.Token);
}
int bytesRead = 0;
Task<int> getBytesTask = null;
var reader = _reader;
if ((reader != null) && (!cancellationToken.IsCancellationRequested) && (!_disposalTokenSource.Token.IsCancellationRequested))
{
getBytesTask = reader.GetBytesAsync(_columnIndex, buffer, offset, count, _readTimeout, combinedTokenSource.Token, out bytesRead);
}
if (getBytesTask == null)
{
_currentTask = null;
if (cancellationToken.IsCancellationRequested)
{
completion.SetCanceled();
}
else if (!CanRead)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
completion.SetResult(bytesRead);
}
if (combinedTokenSource != _disposalTokenSource)
{
combinedTokenSource.Dispose();
}
}
else
{
getBytesTask.ContinueWith((t) =>
{
_currentTask = null;
// If we completed, but _reader is null (i.e. the stream is closed), then report cancellation
if ((t.Status == TaskStatus.RanToCompletion) && (CanRead))
{
completion.SetResult((int)t.Result);
}
else if (t.Status == TaskStatus.Faulted)
{
if (t.Exception.InnerException is SqlException)
{
// Stream.ReadAsync() can't throw a SqlException - so wrap it in an IOException
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
}
else
{
completion.SetException(t.Exception.InnerException);
}
}
else if (!CanRead)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
completion.SetCanceled();
}
if (combinedTokenSource != _disposalTokenSource)
{
combinedTokenSource.Dispose();
}
}, TaskScheduler.Default);
}
}
}
catch (Exception ex)
{
// In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
completion.TrySetException(ex);
Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
throw;
}
}
return completion.Task;
}
public override long Seek(long offset, IO.SeekOrigin origin)
{
throw ADP.NotSupported();
}
public override void SetLength(long value)
{
throw ADP.NotSupported();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw ADP.NotSupported();
}
/// <summary>
/// Forces the stream to act as if it was closed (i.e. CanRead=false and Read() throws)
/// This does not actually close the stream, read off the rest of the data or dispose this
/// </summary>
internal void SetClosed()
{
_disposalTokenSource.Cancel();
_reader = null;
// Wait for pending task
var currentTask = _currentTask;
if (currentTask != null)
{
((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Set the stream as closed
SetClosed();
}
base.Dispose(disposing);
}
/// <summary>
/// Checks the the parameters passed into a Read() method are valid
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
internal static void ValidateReadParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw ADP.ArgumentNull(ADP.ParameterBuffer);
}
if (offset < 0)
{
throw ADP.ArgumentOutOfRange(ADP.ParameterOffset);
}
if (count < 0)
{
throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
}
try
{
if (checked(offset + count) > buffer.Length)
{
throw ExceptionBuilder.InvalidOffsetLength();
}
}
catch (OverflowException)
{
// If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
throw ExceptionBuilder.InvalidOffsetLength();
}
}
}
}
|