Ejemplo n.º 1
0
        public void ReadAsync_MultipleContinuations_Throws(bool onCompleted, bool?continueOnCapturedContext)
        {
            Channel <int> c = CreateChannel();

            ValueTask <int> read = c.Reader.ReadAsync();

            switch (continueOnCapturedContext)
            {
            case null:
                if (onCompleted)
                {
                    read.GetAwaiter().OnCompleted(() => { });
                    Assert.Throws <InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
                }
                else
                {
                    read.GetAwaiter().UnsafeOnCompleted(() => { });
                    Assert.Throws <InvalidOperationException>(() => read.GetAwaiter().UnsafeOnCompleted(() => { }));
                }
                break;

            default:
                if (onCompleted)
                {
                    read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
                    Assert.Throws <InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
                }
                else
                {
                    read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
                    Assert.Throws <InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
                }
                break;
            }
        }
 public async Task ReadAsync_MultipleContinuations_Throws()
 {
     await RunWithConnectedNetworkStreamsAsync((server, client) =>
     {
         var b             = new byte[1];
         ValueTask <int> r = server.ReadAsync(b);
         r.GetAwaiter().OnCompleted(() => { });
         Assert.Throws <InvalidOperationException>(() => r.GetAwaiter().OnCompleted(() => { }));
         return(Task.CompletedTask);
     });
 }
Ejemplo n.º 3
0
        public void Foo10(ValueTaskProvider stream)
        {
            int             bytesRead;
            ValueTask <int> valueTask = stream.ReadAsync();

            if (valueTask.IsCompletedSuccessfully)
            {
                // because they're called after completed successfully, we don't count them
                var once  = valueTask.GetAwaiter().GetResult(); // FN
                var twice = valueTask.GetAwaiter().GetResult(); // FN
            }
        }
Ejemplo n.º 4
0
        public async Task ReadAsync_AwaitThenGetResult_Throws()
        {
            Channel <int> c = CreateChannel();

            ValueTask <int> read = c.Reader.ReadAsync();

            Assert.True(c.Writer.TryWrite(42));
            Assert.Equal(42, await read);
            Assert.Throws <InvalidOperationException>(() => read.GetAwaiter().IsCompleted);
            Assert.Throws <InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
            Assert.Throws <InvalidOperationException>(() => read.GetAwaiter().GetResult());
        }
 public async Task ReadAsync_AwaitMultipleTimes_Throws()
 {
     await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
     {
         var b             = new byte[1];
         ValueTask <int> r = server.ReadAsync(b);
         await client.WriteAsync(new byte[] { 42 });
         Assert.Equal(1, await r);
         Assert.Equal(42, b[0]);
         await Assert.ThrowsAsync <InvalidOperationException>(async() => await r);
         Assert.Throws <InvalidOperationException>(() => r.GetAwaiter().IsCompleted);
         Assert.Throws <InvalidOperationException>(() => r.GetAwaiter().OnCompleted(() => { }));
         Assert.Throws <InvalidOperationException>(() => r.GetAwaiter().GetResult());
     });
 }
        public static RequestFailedException CreateRequestFailedException(this Response response, string message)
        {
            ValueTask <RequestFailedException> messageTask = CreateRequestFailedExceptionAsync(message, response, false);

            Debug.Assert(messageTask.IsCompleted);
            return(messageTask.GetAwaiter().GetResult());
        }
Ejemplo n.º 7
0
        private async Task FlushAsyncAwaited(ValueTask <FlushResult> awaitable, CancellationToken cancellationToken)
        {
            // https://github.com/dotnet/corefxlab/issues/1334
            // Since the flush awaitable doesn't currently support multiple awaiters
            // we need to use a task to track the callbacks.
            // All awaiters get the same task
            lock (_flushLock)
            {
                _flushTask = awaitable;
                if (_flushTcs == null || _flushTcs.Task.IsCompleted)
                {
                    _flushTcs = new TaskCompletionSource <object>();

                    _flushTask.GetAwaiter().OnCompleted(_flushCompleted);
                }
            }

            try
            {
                await _flushTcs.Task;
                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (OperationCanceledException ex)
            {
                Abort(new ConnectionAbortedException(CoreStrings.ConnectionOrStreamAbortedByCancellationToken, ex));
            }
            catch
            {
                // A canceled token is the only reason flush should ever throw.
                Debug.Assert(false);
            }
        }
Ejemplo n.º 8
0
        private async Task FlushAsyncAwaited(ValueTask <FlushResult> awaitable, CancellationToken cancellationToken)
        {
            // https://github.com/dotnet/corefxlab/issues/1334
            // Since the flush awaitable doesn't currently support multiple awaiters
            // we need to use a task to track the callbacks.
            // All awaiters get the same task
            lock (_flushLock)
            {
                _flushTask = awaitable;
                if (_flushTcs == null || _flushTcs.Task.IsCompleted)
                {
                    _flushTcs = new TaskCompletionSource <object>();

                    _flushTask.GetAwaiter().OnCompleted(_flushCompleted);
                }
            }

            try
            {
                await _flushTcs.Task;
                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (OperationCanceledException)
            {
                _completed = true;
                throw;
            }
        }
Ejemplo n.º 9
0
        public async Task ReceiveAllAsync_UnavailableDataCompletesAsynchronously()
        {
            var source = new BufferBlock <int>();

            IAsyncEnumerator <int> e = source.ReceiveAllAsync().GetAsyncEnumerator();

            try
            {
                for (int i = 100; i < 110; i++)
                {
                    ValueTask <bool> vt = e.MoveNextAsync();
                    Assert.False(vt.IsCompleted);
                    Task producer = Task.Run(() => source.Post(i));
                    Assert.True(await vt);
                    await producer;
                    Assert.Equal(i, e.Current);
                }
            }
            finally
            {
                ValueTask vt = e.DisposeAsync();
                Assert.True(vt.IsCompletedSuccessfully);
                vt.GetAwaiter().GetResult();
            }
        }
Ejemplo n.º 10
0
 public void Compliant4(ValueTask <int> valueTask)
 {
     if (valueTask.IsCompletedSuccessfully)
     {
         var once = valueTask.GetAwaiter().GetResult();
     }
 }
        public async Task ReadAllAsync_UnavailableDataCompletesAsynchronously()
        {
            Channel <int> c = CreateChannel();

            IAsyncEnumerator <int> e = c.Reader.ReadAllAsync().GetAsyncEnumerator();

            try
            {
                for (int i = 100; i < 110; i++)
                {
                    ValueTask <bool> vt = e.MoveNextAsync();
                    Assert.False(vt.IsCompleted);
                    Task producer = Task.Run(() => c.Writer.TryWrite(i));
                    Assert.True(await vt);
                    await producer;
                    Assert.Equal(i, e.Current);
                }
            }
            finally
            {
                ValueTask vt = e.DisposeAsync();
                Assert.True(vt.IsCompletedSuccessfully);
                vt.GetAwaiter().GetResult();
            }
        }
            protected override Stream CreateContentReadStream(CancellationToken cancellationToken)
            {
                ValueTask <Stream> task = CreateContentReadStreamAsyncCore(async: false, cancellationToken);

                Debug.Assert(task.IsCompleted);
                return(task.GetAwaiter().GetResult());
            }
Ejemplo n.º 13
0
        public RequestFailedException CreateRequestFailedException(Response response, string?message = null, string?errorCode = null, IDictionary <string, string>?additionalInfo = null, Exception?innerException = null)
        {
            ValueTask <string?> contentTask = ReadContentAsync(response, false);

            Debug.Assert(contentTask.IsCompleted);
            return(CreateRequestFailedExceptionWithContent(response, message, contentTask.GetAwaiter().GetResult(), errorCode, additionalInfo, innerException));
        }
Ejemplo n.º 14
0
        public string CreateRequestFailedMessage(Response response, string?message = null, string?errorCode = null, IDictionary <string, string>?additionalInfo = null)
        {
            ValueTask <string> messageTask = CreateRequestFailedMessageAsync(response, message, errorCode, additionalInfo, false);

            Debug.Assert(messageTask.IsCompleted);
            return(messageTask.GetAwaiter().GetResult());
        }
Ejemplo n.º 15
0
 public static T Run <T>(ValueTask <T> task)
 {
     using (Enter())
     {
         return(task.GetAwaiter().GetResult());
     }
 }
Ejemplo n.º 16
0
 private static void ReThrowOnNSubstituteFault <T>(ValueTask <T> task)
 {
     if (task.IsFaulted && task.AsTask().Exception.InnerExceptions.FirstOrDefault() is SubstituteException)
     {
         task.GetAwaiter().GetResult();
     }
 }
Ejemplo n.º 17
0
 public static void Run(ValueTask task)
 {
     using (Enter())
     {
         task.GetAwaiter().GetResult();
     }
 }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            ValueTask <int> task   = TaskProcedure1();
            int             result = task.GetAwaiter().GetResult();

            Console.WriteLine(result);
        }
    public async Task GetIAsyncEnumerableAsReturnType_MinBatchSize(bool useProxy)
    {
        IAsyncEnumerable <int> enumerable = useProxy
            ? this.clientProxy.Value.GetNumbersInBatchesAsync(this.TimeoutToken)
            : await this.clientRpc.InvokeWithCancellationAsync <IAsyncEnumerable <int> >(nameof(Server.GetNumbersInBatchesAsync), cancellationToken : this.TimeoutToken);

        var enumerator = enumerable.GetAsyncEnumerator(this.TimeoutToken);

        for (int i = 0; i < Server.ValuesReturnedByEnumerables; i++)
        {
            // Assert that the server is always in a state of having produced values to fill a batch.
            Assert.True(this.server.ActuallyGeneratedValueCount % Server.MinBatchSize == 0 || this.server.ActuallyGeneratedValueCount == Server.ValuesReturnedByEnumerables);

            // Assert that the ValueTask completes synchronously within a batch.
            if (i % Server.MinBatchSize == 0)
            {
                // A new batch should be requested here. Allow for an async completion.
                // But avoid asserting that it completed asynchronously or else in certain race conditions the test will fail
                // simply because the async portion happened before the test could check the completion flag.
                Assert.True(await enumerator.MoveNextAsync());
            }
            else
            {
                // Within a batch, the MoveNextAsync call should absolutely complete synchronously.
                ValueTask <bool> valueTask = enumerator.MoveNextAsync();
                Assert.True(valueTask.IsCompleted);
                Assert.True(valueTask.GetAwaiter().GetResult());
            }

            int number = enumerator.Current;
            this.Logger.WriteLine(number.ToString(CultureInfo.InvariantCulture));
        }

        Assert.False(await enumerator.MoveNextAsync());
    }
Ejemplo n.º 20
0
    public void WriteAsync_ThrowsObjectDisposedException()
    {
        this.handler.Dispose();
        ValueTask result = this.handler.WriteAsync(CreateNotifyMessage(), this.TimeoutToken);

        Assert.Throws <ObjectDisposedException>(() => result.GetAwaiter().GetResult());
    }
Ejemplo n.º 21
0
        public async Task WaitToWriteAsync_AwaitThenGetResult_Throws()
        {
            Channel <int> c = CreateFullChannel();

            if (c == null)
            {
                return;
            }

            ValueTask <bool> write = c.Writer.WaitToWriteAsync();
            await c.Reader.ReadAsync();

            Assert.True(await write);
            Assert.Throws <InvalidOperationException>(() => write.GetAwaiter().IsCompleted);
            Assert.Throws <InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
            Assert.Throws <InvalidOperationException>(() => write.GetAwaiter().GetResult());
        }
Ejemplo n.º 22
0
    public void ReadAsync_ThrowsObjectDisposedException()
    {
        this.handler.Dispose();
        ValueTask <JsonRpcMessage> result = this.handler.ReadAsync(this.TimeoutToken);

        Assert.Throws <ObjectDisposedException>(() => result.GetAwaiter().GetResult());
        Assert.Throws <OperationCanceledException>(() => this.handler.ReadAsync(PrecanceledToken).GetAwaiter().GetResult());
    }
        protected internal sealed override HttpResponseMessage Send(HttpRequestMessage request,
                                                                    CancellationToken cancellationToken)
        {
            ValueTask <HttpResponseMessage> sendTask = SendAsync(request, async: false, cancellationToken);

            Debug.Assert(sendTask.IsCompleted);
            return(sendTask.GetAwaiter().GetResult());
        }
Ejemplo n.º 24
0
 /// <summary>
 /// This will check the <see cref="ValueTask{TResult}"/> returned
 /// by a method and ensure it didn't run any async methods.
 /// It then calls GetAwaiter().GetResult() to return the result
 /// Calling .GetResult() will also bubble up an exception if there is one
 /// </summary>
 /// <param name="valueTask">The ValueTask from a method that didn't call any async methods</param>
 /// <returns>The result returned by the method</returns>
 public static TResult CheckSyncValueTaskWorkedAndReturnResult <TResult>(this ValueTask <TResult> valueTask)
 {
     if (!valueTask.IsCompleted)
     {
         throw new InvalidOperationException("Expected a sync task, but got an async task");
     }
     return(valueTask.GetAwaiter().GetResult());
 }
Ejemplo n.º 25
0
            async Task <int> ReadLong(ValueTask <int> task, bool async)
            {
                var read = async
                    ? await task
                    : task.GetAwaiter().GetResult();

                _read += read;
                return(read);
            }
Ejemplo n.º 26
0
        public static T SynchronousGetResult <T>(this ValueTask <T> valueTask)
        {
            if (valueTask.IsCompleted)
            {
                return(valueTask.GetAwaiter().GetResult());
            }

            return(valueTask.AsTask().GetAwaiter().GetResult());
        }
Ejemplo n.º 27
0
 public void SetException_OperationCanceledException_CancelsTask()
 {
     AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder();
     var e = new OperationCanceledException();
     ValueTask<int> vt = b.Task;
     b.SetException(e);
     Assert.True(vt.IsCanceled);
     Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult()));
 }
Ejemplo n.º 28
0
 public void Foo8(ValueTask <object> valueTask)
 {
     if (valueTask.IsCompletedSuccessfully)
     {
         // because they're called after completed successfully, we don't count them
         var bytesRead = valueTask.Result;                   // FN
         var once      = valueTask.GetAwaiter().GetResult(); // FN
     }
 }
Ejemplo n.º 29
0
 public void SetException_AfterAccessTask_FaultsTask()
 {
     AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder();
     var e = new FormatException();
     ValueTask<int> vt = b.Task;
     b.SetException(e);
     Assert.True(vt.IsFaulted);
     Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult()));
 }
        public static void EnsureCompleted(this ValueTask task)
        {
#if DEBUG
            VerifyTaskCompleted(task.IsCompleted);
#endif
#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
            task.GetAwaiter().GetResult();
#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
        }
Ejemplo n.º 31
0
        public async Task Awaiter_OnCompleted()
        {
            // Since ValueTask implements both OnCompleted and UnsafeOnCompleted,
            // OnCompleted typically won't be used by await, so we add an explicit test
            // for it here.

            ValueTask<int> t = new ValueTask<int>(42);
            var tcs = new TaskCompletionSource<bool>();
            t.GetAwaiter().OnCompleted(() => tcs.SetResult(true));
            await tcs.Task;
        }
Ejemplo n.º 32
0
        public void Awaiter_OnCompleted()
        {
            // Since ValueTask implements both OnCompleted and UnsafeOnCompleted,
            // OnCompleted typically won't be used by await, so we add an explicit test
            // for it here.

            ValueTask<int> t = new ValueTask<int>(42);
            var mres = new ManualResetEventSlim();
            t.GetAwaiter().OnCompleted(() => mres.Set());
            Assert.True(mres.Wait(10000));
        }
Ejemplo n.º 33
0
 public async Task Awaiter_ContinuesOnCapturedContext()
 {
     await Task.Run(() =>
     {
         var tsc = new TrackingSynchronizationContext();
         SynchronizationContext.SetSynchronizationContext(tsc);
         try
         {
             ValueTask<int> t = new ValueTask<int>(42);
             var mres = new ManualResetEventSlim();
             t.GetAwaiter().OnCompleted(() => mres.Set());
             Assert.True(mres.Wait(10000));
             Assert.Equal(1, tsc.Posts);
         }
         finally
         {
             SynchronizationContext.SetSynchronizationContext(null);
         }
     });
 }