Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        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);
        }
Esempio n. 3
0
 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);
     }
 }
Esempio n. 4
0
        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);
        }