Exemplo n.º 1
0
 public void GetValueAsyncReturnsCompletedTaskIfAsyncComputationCompletesImmediately()
 {
     // Note, this test may pass even if GetValueAsync posted a task to the threadpool, since the 
     // current thread may context switch out and allow the threadpool to complete the task before
     // we check the state.  However, a failure here definitely indicates a bug in AsyncLazy.
     var lazy = new AsyncLazy<int>(c => Task.FromResult(5), cacheResult: true);
     var t = lazy.GetValueAsync(CancellationToken.None);
     Assert.Equal(TaskStatus.RanToCompletion, t.Status);
     Assert.Equal(5, t.Result);
 }
 public Task <string> GetLaunchSettingsFilePathAsync()
 {
     return(_launchSettingsFilePath.GetValueAsync());
 }
 public async Task <RenameTrackingSolutionSet> RenameSymbolAsync(CancellationToken cancellationToken)
 {
     return(await _renameSymbolResultGetter.GetValueAsync(cancellationToken).ConfigureAwait(false));
 }
Exemplo n.º 4
0
 /// <summary>
 /// Get the singleton instance of the options. Thread safe.
 /// </summary>
 public static Task <T> GetLiveInstanceAsync()
 {
     return(_liveModel.GetValueAsync());
 }
Exemplo n.º 5
0
 /// <summary>
 /// See <see cref="IDynamicEnumValuesGenerator"/>
 /// </summary>
 public async Task <ICollection <IEnumValue> > GetListedValuesAsync()
 {
     return(await listedValues.GetValueAsync().ConfigureAwait(true));
 }
Exemplo n.º 6
0
 public Task <VersionStamp> GetLatestDocumentTopLevelChangeVersionAsync(CancellationToken cancellationToken)
 {
     return(_lazyLatestDocumentTopLevelChangeVersion.GetValueAsync(cancellationToken));
 }
 /// <summary>
 /// Retrieves the set of <see cref="ProjectConfiguration"/>s for the project.
 /// Use this when you actually need all of the <see cref="ProjectConfiguration"/>s;
 /// use <see cref="GetSuggestedConfigurationAsync"/> when you just need any
 /// <see cref="ProjectConfiguration"/>.
 /// </summary>
 public Task <IImmutableSet <ProjectConfiguration>?> GetKnownConfigurationsAsync() => _knownProjectConfigurations.GetValueAsync();
Exemplo n.º 8
0
 public async Task <IReadOnlyList <StaticServer> > GetServersAsync()
 {
     return((await _options.GetValueAsync()).GetServers());
 }
Exemplo n.º 9
0
 public Task <T> GetValueAsync(CancellationToken cancellationToken = default)
 {
     return(_value.GetValueAsync(cancellationToken));
 }
Exemplo n.º 10
0
 public async Task <object> GetValueAsync()
 {
     return(_valueProvider(await _dialogPage.GetValueAsync()));
 }
Exemplo n.º 11
0
        public async Task <Deltas> EmitProjectDeltaAsync(Project project, EmitBaseline baseline, CancellationToken cancellationToken)
        {
            try
            {
                Debug.Assert(!_stoppedAtException);

                var projectChanges = await GetProjectChangesAsync(project, cancellationToken).ConfigureAwait(false);

                var currentCompilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                var allAddedSymbols = await GetAllAddedSymbolsAsync(project, cancellationToken).ConfigureAwait(false);

                var baseActiveStatements = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);

                var baseActiveExceptionRegions = await BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false);

                var pdbStream      = new MemoryStream();
                var updatedMethods = new List <MethodDefinitionHandle>();

                using (var metadataStream = SerializableBytes.CreateWritableStream())
                    using (var ilStream = SerializableBytes.CreateWritableStream())
                    {
                        var result = currentCompilation.EmitDifference(
                            baseline,
                            projectChanges.SemanticEdits,
                            s => allAddedSymbols?.Contains(s) ?? false,
                            metadataStream,
                            ilStream,
                            pdbStream,
                            updatedMethods,
                            cancellationToken);

                        var updatedMethodTokens = updatedMethods.Select(h => MetadataTokens.GetToken(h)).ToArray();

                        // Determine all active statements whose span changed and exception region span deltas.

                        GetActiveStatementAndExceptionRegionSpans(
                            baseline.OriginalMetadata.GetModuleVersionId(),
                            baseActiveStatements,
                            baseActiveExceptionRegions,
                            updatedMethodTokens,
                            _nonRemappableRegions,
                            projectChanges.NewActiveStatements,
                            out var activeStatementsInUpdatedMethods,
                            out var nonRemappableRegions);

                        return(new Deltas(
                                   ilStream.ToArray(),
                                   metadataStream.ToArray(),
                                   pdbStream,
                                   updatedMethodTokens,
                                   projectChanges.LineChanges,
                                   nonRemappableRegions,
                                   activeStatementsInUpdatedMethods,
                                   result));
                    }
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashAndPropagate(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
Exemplo n.º 12
0
 public Task <T> GetValueAsync()
 {
     return(_value.GetValueAsync());
 }
        /// <summary>
        /// Creates a new DockerClient
        /// </summary>
        /// <returns></returns>
        public async Task <IDockerClient> Create(CancellationToken ct = default(CancellationToken))
        {
            var configuration = await _configuration.GetValueAsync(ct);

            return(configuration.CreateClient());
        }
Exemplo n.º 14
0
        /// <summary>
        /// Get all symbols that have a name matching the specified name.
        /// </summary>
        private async Task<ImmutableArray<ISymbol>> FindAsync(
            AsyncLazy<IAssemblySymbol> lazyAssembly,
            string name,
            bool ignoreCase,
            CancellationToken cancellationToken)
        {
            var comparer = GetComparer(ignoreCase);
            var results = ArrayBuilder<ISymbol>.GetInstance();
            IAssemblySymbol assemblySymbol = null;

            foreach (var node in FindNodeIndices(name, comparer))
            {
                cancellationToken.ThrowIfCancellationRequested();
                assemblySymbol = assemblySymbol ?? await lazyAssembly.GetValueAsync(cancellationToken).ConfigureAwait(false);

                Bind(node, assemblySymbol.GlobalNamespace, results, cancellationToken);
            }

            return results.ToImmutableAndFree(); ;
        }
Exemplo n.º 15
0
 private Task InitializeAsync()
 {
     return(_connectionMultiplexer.GetValueAsync());
 }
Exemplo n.º 16
0
        /// <summary>
        /// Slow, linear scan of all the symbols in this assembly to look for matches.
        /// </summary>
        public async Task<IEnumerable<ISymbol>> FindAsync(AsyncLazy<IAssemblySymbol> lazyAssembly, Func<string, bool> predicate, CancellationToken cancellationToken)
        {
            var result = new List<ISymbol>();
            IAssemblySymbol assembly = null;
            for (int i = 0, n = _nodes.Count; i < n; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var node = _nodes[i];
                if (predicate(node.Name))
                {
                    assembly = assembly ?? await lazyAssembly.GetValueAsync(cancellationToken).ConfigureAwait(false);

                    result.AddRange(Bind(i, assembly.GlobalNamespace, cancellationToken));
                }
            }

            return result;
        }
 public async ValueTask <IServiceBroker> GetAsync()
 {
     return(await _serviceBroker.GetValueAsync());
 }
Exemplo n.º 18
0
 public Task <RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken)
 => (_services.Workspace is VisualStudioWorkspace) ? _lazyClient.GetValueAsync(cancellationToken).AsNullable() : SpecializedTasks.Null <RemoteHostClient>();
Exemplo n.º 19
0
        private void SynchronousContinuationsDoNotRunWithinGetValueCallCore(TaskStatus expectedTaskStatus)
        {
            var synchronousComputationStartedEvent        = new ManualResetEvent(initialState: false);
            var synchronousComputationShouldCompleteEvent = new ManualResetEvent(initialState: false);

            var requestCancellationTokenSource = new CancellationTokenSource();

            // First, create an async lazy that will only ever do synchronous computations.
            var lazy = new AsyncLazy <int>(
                asynchronousComputeFunction: c => { throw new Exception("We should not get an asynchronous computation."); },
                synchronousComputeFunction: c =>
            {
                // Notify that the synchronous computation started
                synchronousComputationStartedEvent.Set();

                // And now wait when we should finish
                synchronousComputationShouldCompleteEvent.WaitOne();

                c.ThrowIfCancellationRequested();

                if (expectedTaskStatus == TaskStatus.Faulted)
                {
                    // We want to see what happens if this underlying task faults, so let's fault!
                    throw new Exception("Task blew up!");
                }

                return(42);
            },
                cacheResult: false);

            // Second, start a synchronous request. While we are in the GetValue, we will record which thread is being occupied by the request
            Thread synchronousRequestThread = null;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    synchronousRequestThread = Thread.CurrentThread;
                    lazy.GetValue(requestCancellationTokenSource.Token);
                }
                finally // we do test GetValue in exceptional scenarios, so we should deal with this
                {
                    synchronousRequestThread = null;
                }
            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

            // Wait until this request has actually started
            synchronousComputationStartedEvent.WaitOne();

            // Good, we now have a synchronous request running. An async request should simply create a task that would
            // be completed when the synchronous request completes. We want to assert that if we were to run a continuation
            // from this task that's marked ExecuteSynchronously, we do not run it inline atop the synchronous request.
            bool?      asyncContinuationRanSynchronously = null;
            TaskStatus?observedAntecedentTaskStatus      = null;

            var asyncContinuation = lazy.GetValueAsync(requestCancellationTokenSource.Token).ContinueWith(antecedent =>
            {
                var currentSynchronousRequestThread = synchronousRequestThread;

                asyncContinuationRanSynchronously = currentSynchronousRequestThread != null && currentSynchronousRequestThread == Thread.CurrentThread;
                observedAntecedentTaskStatus      = antecedent.Status;
            },
                                                                                                          CancellationToken.None,
                                                                                                          TaskContinuationOptions.ExecuteSynchronously,
                                                                                                          TaskScheduler.Default);

            // Excellent, the async continuation is scheduled. Let's complete the underlying computation.
            if (expectedTaskStatus == TaskStatus.Canceled)
            {
                requestCancellationTokenSource.Cancel();
            }

            synchronousComputationShouldCompleteEvent.Set();

            // And wait for our continuation to run
            asyncContinuation.Wait();

            Assert.False(asyncContinuationRanSynchronously.Value, "The continuation did not run asynchronously.");
            Assert.Equal(expectedTaskStatus, observedAntecedentTaskStatus.Value);
        }
 /// <summary>
 /// Retrieves a default <see cref="ProjectConfiguration"/> for the project.
 /// </summary>
 public Task <ProjectConfiguration?> GetSuggestedConfigurationAsync() => _defaultProjectConfiguration.GetValueAsync();
 public async Task <Overrides> GetOverridesAsync()
 {
     return(await _lazy.GetValueAsync());
 }
 public Task <RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken)
 => _lazyClient.GetValueAsync(cancellationToken);
Exemplo n.º 23
0
        public async Task <string> GetNameAsync(CancellationToken cancellationToken)
        {
            var result = await resultGetter.GetValueAsync(cancellationToken).ConfigureAwait(false);

            return(result.Name);
        }
 /// <summary>
 /// See <see cref="IDynamicEnumValuesGenerator"/>
 /// </summary>
 public Task <ICollection <IEnumValue> > GetListedValuesAsync()
 {
     return(_listedValues.GetValueAsync());
 }
Exemplo n.º 25
0
        private async Task AddProjectAsync(string project)
        {
            try
            {
                await SafeThreading.JoinableTaskFactory.SwitchToMainThreadAsync();

                GenContext.ToolBox.Shell.ShowStatusBarMessage(string.Format(StringRes.StatusAddingProject, Path.GetFileName(project)));

                var dte = await _dte.GetValueAsync();

                dte.Solution.AddFromFile(project);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(StringRes.ErrorAddingProject, project), ex);
            }
        }
 internal Task <InitializedRemoteService> GetInitializedServiceAsync()
 => _lazyInitializedService.GetValueAsync(_cancellationSource.Token);
Exemplo n.º 27
0
 public Task <Solution> GetSolutionAsync(CancellationToken cancellationToken) =>
 _lazySolution.GetValueAsync(cancellationToken);
Exemplo n.º 28
0
 /// <summary>
 /// Get the singleton instance of the options. Thread safe.
 /// </summary>
 public static Task <T> GetLiveInstanceAsync() => _liveModel.GetValueAsync();
        public async Task RunAsync()
        {
            var lazySlowClass = new AsyncLazy <Slow>(() => new Task <Slow>(() => new Slow()));

            var slow = await lazySlowClass.GetValueAsync();
        }
Exemplo n.º 30
0
        public void GetValueAsyncThatIsCancelledReturnsTaskCancelledWithCorrectToken()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var lazy = new AsyncLazy<object>(c => Task.Run((Func<object>)(() =>
            {
                cancellationTokenSource.Cancel();
                while (true)
                {
                    c.ThrowIfCancellationRequested();
                }
            }), c), cacheResult: true);

            var task = lazy.GetValueAsync(cancellationTokenSource.Token);

            // Now wait until the task completes
            try
            {
                task.Wait();
                AssertEx.Fail(nameof(AsyncLazy<object>.GetValueAsync) + " did not throw an exception.");
            }
            catch (AggregateException ex)
            {
                var operationCancelledException = (OperationCanceledException)ex.Flatten().InnerException;
                Assert.Equal(cancellationTokenSource.Token, operationCancelledException.CancellationToken);
            }
        }
 public Task <IVsOutputWindowPane?> GetOutputWindowPaneAsync()
 {
     return(_outputWindowPane.GetValueAsync());
 }
Exemplo n.º 32
0
        /// <summary>
        /// Get all symbols that have a name matching the specified name.
        /// </summary>
        public async Task<IEnumerable<ISymbol>> FindAsync(
            AsyncLazy<IAssemblySymbol> lazyAssembly,
            string name,
            bool ignoreCase,
            CancellationToken cancellationToken)
        {
            var comparer = GetComparer(ignoreCase);
            var result = new List<ISymbol>();
            IAssemblySymbol assemblySymbol = null;

            foreach (var node in FindNodes(name, comparer))
            {
                cancellationToken.ThrowIfCancellationRequested();
                assemblySymbol = assemblySymbol ?? await lazyAssembly.GetValueAsync(cancellationToken).ConfigureAwait(false);

                result.AddRange(Bind(node, assemblySymbol.GlobalNamespace, cancellationToken));
            }

            return result;
        }
Exemplo n.º 33
0
 public Task <SyntaxTreeBase> GetSyntaxTreeAsync(CancellationToken cancellationToken)
 {
     return(_lazySyntaxTree.GetValueAsync(cancellationToken));
 }
Exemplo n.º 34
0
        public void CancellationDuringInlinedComputationFromGetValueAsyncStillCachesResult()
        {
            using (new StopTheThreadPoolContext())
            {
                int computations = 0;
                var requestCancellationTokenSource = new CancellationTokenSource();

                var lazy = new AsyncLazy<object>(c =>
                    {
                        Interlocked.Increment(ref computations);

                        // We do not want to ever use the cancellation token that we are passed to this
                        // computation. Rather, we will ignore it but cancel any request that is
                        // outstanding.
                        requestCancellationTokenSource.Cancel();

                        return Task.FromResult(new object());
                    }, cacheResult: true);

                // Do a first request. Even though we will get a cancellation during the evaluation,
                // since we handed a result back, that result must be cached.
                var firstRequestResult = lazy.GetValueAsync(requestCancellationTokenSource.Token).Result;

                // And a second request. We'll let this one complete normally.
                var secondRequestResult = lazy.GetValueAsync(CancellationToken.None).Result;

                // We should have gotten the same cached result, and we should have only computed once.
                Assert.Same(secondRequestResult, firstRequestResult);
                Assert.Equal(1, computations);
            }
        }
Exemplo n.º 35
0
 public Task <Compilation> GetCompilationAsync(string language, CancellationToken cancellationToken)
 => language == LanguageNames.CSharp ? csbuild.GetValueAsync(cancellationToken) : vbbuild.GetValueAsync(cancellationToken);
Exemplo n.º 36
0
        private void SynchronousContinuationsDoNotRunWithinGetValueCallCore(TaskStatus expectedTaskStatus)
        {
            var synchronousComputationStartedEvent = new ManualResetEvent(initialState: false);
            var synchronousComputationShouldCompleteEvent = new ManualResetEvent(initialState: false);

            var requestCancellationTokenSource = new CancellationTokenSource();

            // First, create an async lazy that will only ever do synchronous computations.
            var lazy = new AsyncLazy<int>(
                asynchronousComputeFunction: c => { throw new Exception("We should not get an asynchronous computation."); },
                synchronousComputeFunction: c =>
                {
                    // Notify that the synchronous computation started
                    synchronousComputationStartedEvent.Set();

                    // And now wait when we should finish
                    synchronousComputationShouldCompleteEvent.WaitOne();

                    c.ThrowIfCancellationRequested();

                    if (expectedTaskStatus == TaskStatus.Faulted)
                    {
                        // We want to see what happens if this underlying task faults, so let's fault!
                        throw new Exception("Task blew up!");
                    }

                    return 42;
                },
                cacheResult: false);

            // Second, start a synchronous request. While we are in the GetValue, we will record which thread is being occupied by the request
            Thread synchronousRequestThread = null;
            Task.Factory.StartNew(() =>
            {
                try
                {
                    synchronousRequestThread = Thread.CurrentThread;
                    lazy.GetValue(requestCancellationTokenSource.Token);
                }
                finally // we do test GetValue in exceptional scenarios, so we should deal with this
                {
                    synchronousRequestThread = null;
                }
            }, CancellationToken.None);

            // Wait until this request has actually started
            synchronousComputationStartedEvent.WaitOne();

            // Good, we now have a synchronous request running. An async request should simply create a task that would
            // be completed when the synchronous request completes. We want to assert that if we were to run a continuation
            // from this task that's marked ExecuteSynchronously, we do not run it inline atop the synchronous request.
            bool? asyncContinuationRanSynchronously = null;
            TaskStatus? observedAntecedentTaskStatus = null;

            var asyncContinuation = lazy.GetValueAsync(requestCancellationTokenSource.Token).ContinueWith(antecedent =>
                {
                    var currentSynchronousRequestThread = synchronousRequestThread;

                    asyncContinuationRanSynchronously = currentSynchronousRequestThread != null && currentSynchronousRequestThread == Thread.CurrentThread;
                    observedAntecedentTaskStatus = antecedent.Status;
                },
                CancellationToken.None,
                TaskContinuationOptions.ExecuteSynchronously,
                TaskScheduler.Default);

            // Excellent, the async continuation is scheduled. Let's complete the underlying computation.
            if (expectedTaskStatus == TaskStatus.Canceled)
            {
                requestCancellationTokenSource.Cancel();
            }

            synchronousComputationShouldCompleteEvent.Set();

            // And wait for our continuation to run
            asyncContinuation.Wait();

            Assert.False(asyncContinuationRanSynchronously.Value, "The continuation did not run asynchronously.");
            Assert.Equal(expectedTaskStatus, observedAntecedentTaskStatus.Value);
        }
        public async Task <bool> EntityExistsAsync(string filePath)
        {
            var workspaceService = await _workspaceService.GetValueAsync();

            return(await workspaceService.EntityExistsAsync(filePath));
        }