public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(TaskEx.FromCancellation <int>(cancellationToken)); } var token = new PooledToken <bool>(_pool.Get()); var e = token.SocketAsyncEventArgs; e.SetBuffer(buffer, offset, count); e.Completed += WriteCompleted; try { if (!Socket.SendAsync(e)) { WriteCompleted(Socket, e); } } catch (Exception ex) { ClearWrite(e); token.TaskCompletionSource.SetException(ex); } return(token.Task); }
public override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(TaskEx.FromCancellation <int>(cancellationToken)); } var token = new PooledToken <int>(_pool.Get()); var e = token.SocketAsyncEventArgs; e.SetBuffer(buffer, offset, count); e.Completed += ReadCompleted; //_socket.Available try { if (!Socket.ReceiveAsync(e)) { ReadCompleted(Socket, e); } } catch (Exception ex) { ClearRead(e); token.TaskCompletionSource.SetException(ex); } return(token.Task); }
public void FromCancellationWorks() { Assert.False(TaskEx.FromCancellation(CancellationToken.None).IsCanceled); Assert.True(TaskEx.FromCancellation(new CancellationToken(true)).IsCanceled); using (var cts = new CancellationTokenSource()) { var task = TaskEx.FromCancellation <int>(cts.Token); Assert.False(task.IsCanceled); cts.Cancel(); Assert.True(task.IsCanceled); } }
public async Task ThenWorks() { Assert.Equal(2.5, Task.FromResult(5).Then(x => x / 2.0).Result); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await Throw(0).Then(x => x / 2.0); }); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await Throw(1).Then(x => x / 2.0); }); Assert.True(TaskEx.FromCancellation <int>(new CancellationToken(true)).Then(x => x / 2.0).IsCanceled); }