public void AsTask_ConstructedCanceledToken_CancelsTask()
        {
            AsyncContext.Run(async () =>
            {
                var token = new CancellationToken(true);
                var task = token.AsTask();

                await AssertEx.ThrowsExceptionAsync<TaskCanceledException>(task);
            });
        }
        internal static async Task InitAdAsync(this IVpaid vpaid, double width, double height, string viewMode, int desiredBitrate, string creativeData, string environmentVariables, CancellationToken cancellationToken)
#endif
        {
            var errorTask = vpaid.GetErrorTask(cancellationToken);
            var loadedTask = vpaid.GetLoadedTask(cancellationToken);
            var cancellationTask = cancellationToken.AsTask();

            vpaid.InitAd(width, height, viewMode, desiredBitrate, creativeData, environmentVariables);

#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
            var completedTask = await TaskEx.WhenAny(loadedTask, errorTask, cancellationTask);
#else
            var completedTask = await Task.WhenAny(loadedTask, errorTask, cancellationTask);
#endif
            if (completedTask == errorTask)
            {
                throw errorTask.Result;
            }
            else if (completedTask == cancellationTask)
            {
                vpaid.StopAd();
            }
            cancellationToken.ThrowIfCancellationRequested();
        }
 public static Task WaitAsync(this AsyncCountdownEvent countdownEvent, CancellationToken cancellationToken = default(CancellationToken)) {
     return Task.WhenAny(countdownEvent.WaitAsync(), cancellationToken.AsTask());
 }
        async Task ReadResponseAsync(IMediaParser mediaParser, IWebStreamResponse webStreamResponse, WebResponse webResponse, QueueThrottle throttle, CancellationToken cancellationToken)
        {
            //Debug.WriteLine("SingleStreamMediaManager.ReadResponseAsync()");

            var buffer = new byte[16 * 1024];

            var cancellationTask = cancellationToken.AsTask();

            try
            {
                var segmentMetadata = _webMetadataFactory.CreateSegmentMetadata(webResponse);

                mediaParser.StartSegment(segmentMetadata);

                using (var stream = await webStreamResponse.GetStreamAsync(cancellationToken).ConfigureAwait(false))
                {
                    for (; ; )
                    {
                        var waitTask = throttle.WaitAsync();

                        if (!waitTask.IsCompleted)
                        {
                            await Task.WhenAny(waitTask, cancellationTask).ConfigureAwait(false);

                            cancellationToken.ThrowIfCancellationRequested();
                        }

                        var length = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);

                        if (length <= 0)
                            return;

                        mediaParser.ProcessData(buffer, 0, length);
                    }
                }
            }
            finally
            {
                mediaParser.ProcessEndOfData();

                //Debug.WriteLine("SingleStreamMediaManager.ReadResponseAsync() done");
            }
        }
        async Task SimplePlayAsync(ContentType contentType, IWebReader webReader, IWebStreamResponse webStreamResponse, WebResponse webResponse, TaskCompletionSource<bool> configurationTaskCompletionSource, CancellationToken cancellationToken)
        {
            try
            {
                _mediaStreamConfigurator.Initialize();

                _mediaStreamConfigurator.MediaManager = this;

                var mediaParser = await _mediaParserFactory.CreateAsync(new MediaParserParameters(), contentType, cancellationToken).ConfigureAwait(false);

                if (null == mediaParser)
                    throw new NotSupportedException("Unsupported content type: " + contentType);

                State = MediaManagerState.Opening;

                EventHandler configurationComplete = null;

                configurationComplete = (sender, args) =>
                {
                    // ReSharper disable once AccessToModifiedClosure
                    mediaParser.ConfigurationComplete -= configurationComplete;

                    configurationTaskCompletionSource.TrySetResult(true);
                };

                mediaParser.ConfigurationComplete += configurationComplete;

                using (var bufferingManager = _bufferingManagerFactory())
                {
                    var throttle = new QueueThrottle();

                    bufferingManager.Initialize(throttle, _mediaStreamConfigurator.CheckForSamples);

                    mediaParser.Initialize(bufferingManager);

                    var streamMetadata = _webMetadataFactory.CreateStreamMetadata(webResponse);

                    mediaParser.InitializeStream(streamMetadata);

                    Task reader = null;

                    try
                    {
                        using (webReader)
                        {
                            try
                            {
                                if (null == webStreamResponse)
                                    webStreamResponse = await webReader.GetWebStreamAsync(null, false, cancellationToken, response: webResponse).ConfigureAwait(false);

                                reader = ReadResponseAsync(mediaParser, webStreamResponse, webResponse, throttle, cancellationToken);

                                await Task.WhenAny(configurationTaskCompletionSource.Task, cancellationToken.AsTask()).ConfigureAwait(false);

                                cancellationToken.ThrowIfCancellationRequested();

                                await _mediaStreamConfigurator.PlayAsync(mediaParser.MediaStreams, null, cancellationToken).ConfigureAwait(false);

                                State = MediaManagerState.Playing;

                                await reader.ConfigureAwait(false);

                                reader = null;
                            }
                            finally
                            {
                                if (null != webStreamResponse)
                                    webStreamResponse.Dispose();
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    { }
                    catch (Exception ex)
                    {
                        var message = ex.ExtendedMessage();

                        Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() failed: " + message);

                        SetMediaState(MediaManagerState.Error, message);
                    }

                    State = MediaManagerState.Closing;

                    if (null != reader)
                    {
                        try
                        {
                            await reader.ConfigureAwait(false);
                        }
                        catch (OperationCanceledException)
                        { }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() reader failed: " + ex.ExtendedMessage());
                        }
                    }

                    mediaParser.ConfigurationComplete -= configurationComplete;

                    mediaParser.EnableProcessing = false;
                    mediaParser.FlushBuffers();

                    bufferingManager.Flush();

                    bufferingManager.Shutdown(throttle);

                    await _mediaStreamConfigurator.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() cleanup failed: " + ex.ExtendedMessage());
            }

            _mediaStreamConfigurator.MediaManager = null;

            if (!configurationTaskCompletionSource.Task.IsCompleted)
                configurationTaskCompletionSource.TrySetCanceled();

            State = MediaManagerState.Closed;

            await _reportStateTask.WaitAsync().ConfigureAwait(false);
        }
        internal static async Task StopAdAsync(this IVpaid vpaid, CancellationToken cancellationToken)
#endif
        {
            var errorTask = vpaid.GetErrorTask(cancellationToken);
            var stoppedTask = vpaid.GetStoppedTask(cancellationToken);
            var cancellationTask = cancellationToken.AsTask();

            vpaid.StopAd();
#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
            var completedTask = await TaskEx.WhenAny(stoppedTask, errorTask, cancellationTask);
#else
            var completedTask = await Task.WhenAny(stoppedTask, errorTask, cancellationTask);
#endif
            if (completedTask == errorTask)
            {
                throw errorTask.Result;
            }
            cancellationToken.ThrowIfCancellationRequested();
        }
        internal static async Task<bool> PlayAdAsync(this IVpaid vpaid, CancellationToken cancellationToken)
#endif
        {
            var errorTask = vpaid.GetErrorTask(cancellationToken);
            var stoppedTask = vpaid.GetStoppedTask(cancellationToken);
            var approachingEndTask = vpaid.GetApproachingEndTask(cancellationToken);
            var cancellationTask = cancellationToken.AsTask();

#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
            var completedTask = await TaskEx.WhenAny(stoppedTask, approachingEndTask, errorTask, cancellationTask);
#else
            var completedTask = await Task.WhenAny(stoppedTask, approachingEndTask, errorTask, cancellationTask);
#endif
            bool result = true;
            if (completedTask == errorTask)
            {
                throw errorTask.Result;
            }
            else if (completedTask == cancellationTask)
            {
                vpaid.StopAd();
            }
            else if (completedTask == approachingEndTask)
            {
                result = false;
            }
            cancellationToken.ThrowIfCancellationRequested();
            return result;
        }