public async Task<IEnumerable<ISymbol>> FindAsync( SearchQuery query, AsyncLazy<IAssemblySymbol> lazyAssembly, SymbolFilter filter, CancellationToken cancellationToken) { return SymbolFinder.FilterByCriteria( await FindAsyncWorker(query, lazyAssembly, cancellationToken).ConfigureAwait(false), filter); }
internal ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices) { Contract.ThrowIfNull(projectInfo); Contract.ThrowIfNull(languageServices); Contract.ThrowIfNull(solutionServices); _languageServices = languageServices; _solutionServices = solutionServices; _projectInfo = FixProjectInfo(projectInfo); _documentIds = _projectInfo.Documents.Select(d => d.Id).ToImmutableArray(); _additionalDocumentIds = this.ProjectInfo.AdditionalDocuments.Select(d => d.Id).ToImmutableArray(); var docStates = ImmutableDictionary.CreateRange<DocumentId, DocumentState>( _projectInfo.Documents.Select(d => new KeyValuePair<DocumentId, DocumentState>(d.Id, CreateDocument(this.ProjectInfo, d, languageServices, solutionServices)))); _documentStates = docStates; var additionalDocStates = ImmutableDictionary.CreateRange<DocumentId, TextDocumentState>( _projectInfo.AdditionalDocuments.Select(d => new KeyValuePair<DocumentId, TextDocumentState>(d.Id, TextDocumentState.Create(d, solutionServices)))); _additionalDocumentStates = additionalDocStates; _lazyLatestDocumentVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(docStates, additionalDocStates, c), cacheResult: true); _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(docStates, additionalDocStates, c), cacheResult: true); }
public async Task AsyncLazy_MultipleAwaitersOnlyInvokeFuncOnce() { //Arrange int invokeCount = 0; var expected = A.Dummy<int>(); var mre = new ManualResetEvent(false); Func<int> func = () => { Interlocked.Increment(ref invokeCount); mre.WaitOne(); return expected; }; var lazy = new AsyncLazy<int>(func); var task1 = Task.Factory.StartNew(async () => await lazy).Result; var task2 = Task.Factory.StartNew(async () => await lazy).Result; task1.IsCompleted.Should().BeFalse(); task2.IsCompleted.Should().BeFalse(); //Act mre.Set(); var results = await Task.WhenAll(task1, task2); //Assert results.Should().NotBeEmpty().And.HaveCount(2).And.ContainInOrder(new[] { expected, expected }); invokeCount.Should().Be(1); }
private static void TestSyntaxTreeFactoryService(ISyntaxTreeFactoryService service, string text, string fileName) { var parseOptions = service.GetDefaultParseOptions(); var workspaceServices = new TestWorkspaceServiceProvider(); var tree = service.ParseSyntaxTree( fileName, parseOptions, SourceText.From(text), CancellationToken.None); var textAndVersion = TextAndVersion.Create( tree.GetText(), VersionStamp.Create(), fileName); var valueSource = new AsyncLazy<TextAndVersion>(textAndVersion); var recoverableTree = service.CreateRecoverableTree( tree.FilePath, tree.Options, valueSource, tree.GetRoot()); workspaceServices.GetService<ISyntaxTreeCacheService>().Clear(); var trivia = tree.GetRoot().GetLeadingTrivia().First(); var actualTrivia = recoverableTree.GetRoot().GetLeadingTrivia().First(); Assert.Equal(trivia.ToFullString(), actualTrivia.ToFullString()); }
static MsBuildMap() { TaskClasses = new AsyncLazy<Dictionary<string, MSBuildTaskType>>(() => { var _taskClasses = new Dictionary<string, MSBuildTaskType>(); // ensure a few assemblies are loaded. AppDomain.CurrentDomain.Load(new AssemblyName("Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")); AppDomain.CurrentDomain.Load(new AssemblyName("Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")); AppDomain.CurrentDomain.Load(new AssemblyName("Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var asm in assemblies) { var tasks = asm.GetTypes().Where(each => each.GetInterfaces().Contains(typeof (ITask))).Where(each => each.IsPublic); foreach (var t in tasks) { var properties = t.GetProperties().Where(each => !_ignoreProperties.Contains(each.Name)).ToArray(); if (!_taskClasses.Keys.Contains(t.Name)) { _taskClasses.Add(t.Name.ToLower(), new MSBuildTaskType { TaskClass = t, Outputs = properties.Where(each => each.GetCustomAttributes(true).Any(attr => attr.GetType().Name == "OutputAttribute")).Select(each => each.Name).ToArray(), RequiredInputs = properties.Where(each => each.GetCustomAttributes(true).Any(attr => attr.GetType().Name == "RequiredAttribute")).Select(each => each.Name).ToArray(), OptionalInputs = properties.Where(each => each.GetCustomAttributes(true).All(attr => attr.GetType().Name != "OutputAttribute" && attr.GetType().Name != "RequiredAttribute")).Select(each => each.Name).ToArray() }); } } } return _taskClasses; }); }
private ProjectState( ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices, IEnumerable<DocumentId> documentIds, IEnumerable<DocumentId> additionalDocumentIds, ImmutableDictionary<DocumentId, DocumentState> documentStates, ImmutableDictionary<DocumentId, TextDocumentState> additionalDocumentStates, AsyncLazy<VersionStamp> lazyLatestDocumentVersion, AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion, ValueSource<ProjectStateChecksums> lazyChecksums) { _projectInfo = projectInfo; _solutionServices = solutionServices; _languageServices = languageServices; _documentIds = documentIds.ToImmutableReadOnlyListOrEmpty(); _additionalDocumentIds = additionalDocumentIds.ToImmutableReadOnlyListOrEmpty(); _documentStates = documentStates; _additionalDocumentStates = additionalDocumentStates; _lazyLatestDocumentVersion = lazyLatestDocumentVersion; _lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion; // for now, let it re-calculate if anything changed. // TODO: optimize this so that we only re-calcuate checksums that are actually changed _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); }
public async Task AsyncLazy_Await_ReturnsFuncValue() { Func<int> func = () => 13; var lazy = new AsyncLazy<int>(func); var result = await lazy; Assert.AreEqual(13, result); }
public Usage() { sharedResource = new AsyncLazy<int>(async () => { await Task.Delay(1000); return 13; }); }
public AzureLocation(AzureDriveInfo driveInfo, Path path, IListBlobItem cloudItem) { _driveInfo = driveInfo; Path = path; Path.Validate(); if (cloudItem != null) { _cloudItem = new AsyncLazy<IListBlobItem>(() => { if (cloudItem is CloudBlockBlob) { (cloudItem as CloudBlockBlob).FetchAttributes(); } return cloudItem; }); } else { if (IsRootNamespace || IsAccount || IsContainer) { // azure namespace mount. _cloudItem = new AsyncLazy<IListBlobItem>(() => null); return; } _cloudItem = new AsyncLazy<IListBlobItem>(() => { if (CloudContainer == null) { return null; } // not sure if it's a file or a directory. if (path.EndsWithSlash) { // can't be a file! CloudContainer.GetDirectoryReference(Path.SubPath); } // check to see if it's a file. ICloudBlob blobRef = null; try { blobRef = CloudContainer.GetBlobReferenceFromServer(Path.SubPath); if (blobRef != null && blobRef.BlobType == BlobType.BlockBlob) { blobRef.FetchAttributes(); return blobRef; } } catch { } // well, we know it's not a file, container, or account. // it could be a directory (but the only way to really know that is to see if there is any files that have this as a parent path) var dirRef = CloudContainer.GetDirectoryReference(Path.SubPath); if (dirRef.ListBlobs().Any()) { return dirRef; } blobRef = CloudContainer.GetBlockBlobReference(Path.SubPath); if (blobRef != null && blobRef.BlobType == BlobType.BlockBlob) { return blobRef; } // it really didn't match anything, we'll return the reference to the blob in case we want to write to it. return blobRef; }); _cloudItem.InitializeAsync(); } }
public void SynchronousRequestShouldCacheValueWithAsynchronousComputeFunction() { var lazy = new AsyncLazy<object>(c => Task.FromResult(new object()), cacheResult: true); var firstRequestResult = lazy.GetValue(CancellationToken.None); var secondRequestResult = lazy.GetValue(CancellationToken.None); Assert.Same(secondRequestResult, firstRequestResult); }
public LazyRemoteService(InteractiveHost host, InteractiveHostOptions options, int instanceId, bool skipInitialization) { InitializedService = new AsyncLazy<InitializedRemoteService>(TryStartAndInitializeProcessAsync, cacheResult: true); CancellationSource = new CancellationTokenSource(); InstanceId = instanceId; Options = options; Host = host; SkipInitialization = skipInitialization; }
public void AsyncLazy_NeverAwaited_DoesNotCallFunc() { Func<int> func = () => { Assert.Fail(); return 13; }; var lazy = new AsyncLazy<int>(func); }
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); }
static RethinkDBClient() { //by default convert all enums to strings (or else config assembler will default to int32). RethinkDb.Newtonsoft.Configuration.ConfigurationAssembler.DefaultJsonSerializerSettings.Converters.Add( new StringEnumConverter() ); DefaultConnectionCache = new AsyncLazy<IConnection>( async () => { return await ConfigurationAssembler.CreateConnectionFactory( RethinkDBClusterName ).GetAsync(); } ); }
public async Task LoadAsync() { _aData = new AsyncLazy<string>(() => LoadAAsync()); _bData = new AsyncLazy<string>(() => LoadBAsync()); _cData = new AsyncLazy<string>(() => LoadCAsync()); _dData = new AsyncLazy<string>(() => LoadDAsync()); _eData = new AsyncLazy<string>(() => LoadEAsync()); await Task.WhenAll(_eData.Value, _dData.Value, _cData.Value, _bData.Value, _aData.Value); Console.WriteLine("A: {0}, B: {1}, C: {2}, D: {3}, E: {4}", _aData.Value.Result, _bData.Value.Result, _cData.Value.Result, _dData.Value.Result, _eData.Value.Result); }
public RemoteHostClientService(Workspace workspace) { var remoteHostClientFactory = workspace.Services.GetService<IRemoteHostClientFactory>(); if (remoteHostClientFactory == null) { // no implementation of remote host client return; } _lazyInstance = new AsyncLazy<RemoteHostClient>(c => remoteHostClientFactory.CreateAsync(workspace, c), cacheResult: true); }
public void AsyncLazy_NeverAwaitedDoesNotCallFunc() { //Arrange Func<int> func = () => { Assert.Fail(); return A.Dummy<int>(); }; //Assert var lazy = new AsyncLazy<int>(func); }
public async void Must_initialize_only_once() { int count = 0; var systemUnderTest = new AsyncLazy<int>(() => count++); #pragma warning disable 168 int value1 = await systemUnderTest.Value; int value2 = await systemUnderTest.Value; #pragma warning restore 168 Assert.That(count, Is.EqualTo(1)); }
public async Task AsyncLazy_AwaitReturnsFuncValue() { var expected = A.Dummy<int>(); Func<int> func = () => { return expected; }; var lazy = new AsyncLazy<int>(func); var result = await lazy; result.Should().Be(expected); }
public async Task AsyncLazy_StartCallsFunc() { var tcs = new TaskCompletionSource<int>(); Func<int> func = () => { tcs.SetResult(A.Dummy<int>()); return A.Dummy<int>(); }; var lazy = new AsyncLazy<int>(func); lazy.Start(); var res = await tcs.Task; }
public async Task AsyncLazy_Start_CallsFunc() { var tcs = new TaskCompletionSource<bool>(); Func<int> func = () => { tcs.SetResult(true); return 13; }; var lazy = new AsyncLazy<int>(func); lazy.Start(); await tcs.Task; }
/// <summary> /// Finds symbols in this assembly that match the provided name in a fuzzy manner. /// </summary> public async Task<IEnumerable<ISymbol>> FuzzyFindAsync(AsyncLazy<IAssemblySymbol> lazyAssembly, string name, CancellationToken cancellationToken) { var similarNames = _spellChecker.FindSimilarWords(name); var result = new List<ISymbol>(); foreach (var similarName in similarNames) { var symbols = await FindAsync(lazyAssembly, similarName, ignoreCase: true, cancellationToken: cancellationToken).ConfigureAwait(false); result.AddRange(symbols); } return result; }
public RenameTrackingCommitter( StateMachine stateMachine, SnapshotSpan snapshotSpan, IEnumerable<IRefactorNotifyService> refactorNotifyServices, ITextUndoHistoryRegistry undoHistoryRegistry, string displayText) { _stateMachine = stateMachine; _snapshotSpan = snapshotSpan; _refactorNotifyServices = refactorNotifyServices; _undoHistoryRegistry = undoHistoryRegistry; _displayText = displayText; _renameSymbolResultGetter = new AsyncLazy<RenameTrackingSolutionSet>(c => RenameSymbolWorkerAsync(c), cacheResult: true); }
public void AsyncLazy_CallsFuncOnThreadPool() { var testThread = Thread.CurrentThread.ManagedThreadId; var funcThread = testThread; Func<int> func = () => { funcThread = Thread.CurrentThread.ManagedThreadId; return 13; }; var lazy = new AsyncLazy<int>(func); Task.Run(async () => await lazy).Wait(); Assert.AreNotEqual(testThread, funcThread); }
public CacheResponse(IResponse response) { response.ThrowIfNull("response"); _statusCode = response.StatusCode; _contentType = response.ContentType; _charset = response.Charset ?? DefaultCharset; _contentEncoding = response.ContentEncoding ?? _defaultContentEncoding; _headers = response.Headers.Select(arg => arg.Clone()).ToArray(); _headerEncoding = response.HeaderEncoding ?? _defaultHeaderEncoding; _cookies = response.Cookies.Select(arg => arg.Clone()).ToArray(); _cachePolicy = response.CachePolicy.Clone(); _skipIisCustomErrors = response.SkipIisCustomErrors; _content = new AsyncLazy<byte[]>(() => response.GetContentAsync()); }
public void AsyncLazy_Start_CallsFunc() { AsyncContext.Run(async () => { var tcs = new TaskCompletionSource(); Func<int> func = () => { tcs.SetResult(); return 13; }; var lazy = new AsyncLazy<int>(func); lazy.Start(); await tcs.Task; }); }
private ProjectState( ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices, IEnumerable<DocumentId> documentIds, ImmutableDictionary<DocumentId, DocumentState> documentStates, AsyncLazy<VersionStamp> lazyLatestDocumentVersion, AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion) { this.projectInfo = projectInfo; this.solutionServices = solutionServices; this.languageServices = languageServices; this.documentIds = documentIds.ToImmutableReadOnlyListOrEmpty(); this.documentStates = documentStates; this.lazyLatestDocumentVersion = lazyLatestDocumentVersion; this.lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion; }
private ProjectState( ProjectInfo projectInfo, ILanguageServiceProvider languageServices, SolutionServices solutionServices, ImmutableList<DocumentId> documentIds, ImmutableDictionary<DocumentId, DocumentState> documentStates, AsyncLazy<VersionStamp> lazyLatestDocumentVersion, AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion) { this.projectInfo = projectInfo; this.solutionServices = solutionServices; this.languageServices = languageServices; this.documentIds = documentIds; this.documentStates = documentStates; this.lazyLatestDocumentVersion = lazyLatestDocumentVersion; this.lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion; }
public VersionManager() { this.currentVersion = new AsyncLazy<Version>(async () => { Version result = null; try { WebClient client = new WebClient(); var parts = (await client.DownloadStringTaskAsync(Settings.Default.CurrentVersionUrl)).Split(new[] { '.' }).Select(x => Int32.Parse(x)).ToArray(); result = new Version(parts[0], parts[1], parts[2]); } catch (WebException) { } return result; }); }
public Task<IEnumerable<ISymbol>> FindAsync(SearchQuery query, AsyncLazy<IAssemblySymbol> lazyAssembly, CancellationToken cancellationToken) { // If the query has a specific string provided, then call into the SymbolTreeInfo // helpers optimized for lookup based on an exact name. switch (query.Kind) { case SearchKind.Exact: return this.FindAsync(lazyAssembly, query.Name, ignoreCase: false, cancellationToken: cancellationToken); case SearchKind.ExactIgnoreCase: return this.FindAsync(lazyAssembly, query.Name, ignoreCase: true, cancellationToken: cancellationToken); case SearchKind.Fuzzy: return this.FuzzyFindAsync(lazyAssembly, query.Name, cancellationToken); case SearchKind.Custom: // Otherwise, we'll have to do a slow linear search over all possible symbols. return this.FindAsync(lazyAssembly, query.GetPredicate(), cancellationToken); } throw new InvalidOperationException(); }
public LocalUserRegistryOptionPersisterProvider( [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider) { _lazyPersister = new(_ => LocalUserRegistryOptionPersister.CreateAsync(serviceProvider), cacheResult : true); }
// for testing purposes internal static void ResetAsyncValues() { IsTransitiveOriginExpEnabled = new(() => IsExperimentEnabledAsync(ExperimentationConstants.TransitiveDependenciesInPMUI), NuGetUIThreadHelper.JoinableTaskFactory); }
public CrossPartitionRangePageAsyncEnumerator( IFeedRangeProvider feedRangeProvider, CreatePartitionRangePageAsyncEnumerator <TPage, TState> createPartitionRangeEnumerator, IComparer <PartitionRangePageAsyncEnumerator <TPage, TState> > comparer, int?maxConcurrency, CancellationToken cancellationToken, CrossFeedRangeState <TState> state = default) { this.feedRangeProvider = feedRangeProvider ?? throw new ArgumentNullException(nameof(feedRangeProvider)); this.createPartitionRangeEnumerator = createPartitionRangeEnumerator ?? throw new ArgumentNullException(nameof(createPartitionRangeEnumerator)); this.cancellationToken = cancellationToken; this.lazyEnumerators = new AsyncLazy <IQueue <PartitionRangePageAsyncEnumerator <TPage, TState> > >(async(ITrace trace, CancellationToken token) => { ReadOnlyMemory <FeedRangeState <TState> > rangeAndStates; if (state != default) { rangeAndStates = state.Value; } else { // Fan out to all partitions with default state List <FeedRangeEpk> ranges = await feedRangeProvider.GetFeedRangesAsync(trace, token); List <FeedRangeState <TState> > rangesAndStatesBuilder = new List <FeedRangeState <TState> >(ranges.Count); foreach (FeedRangeInternal range in ranges) { rangesAndStatesBuilder.Add(new FeedRangeState <TState>(range, default)); } rangeAndStates = rangesAndStatesBuilder.ToArray(); } List <BufferedPartitionRangePageAsyncEnumerator <TPage, TState> > bufferedEnumerators = new List <BufferedPartitionRangePageAsyncEnumerator <TPage, TState> >(rangeAndStates.Length); for (int i = 0; i < rangeAndStates.Length; i++) { FeedRangeState <TState> feedRangeState = rangeAndStates.Span[i]; PartitionRangePageAsyncEnumerator <TPage, TState> enumerator = createPartitionRangeEnumerator(feedRangeState); BufferedPartitionRangePageAsyncEnumerator <TPage, TState> bufferedEnumerator = new BufferedPartitionRangePageAsyncEnumerator <TPage, TState>(enumerator, cancellationToken); bufferedEnumerators.Add(bufferedEnumerator); } if (maxConcurrency.HasValue) { await ParallelPrefetch.PrefetchInParallelAsync(bufferedEnumerators, maxConcurrency.Value, trace, token); } IQueue <PartitionRangePageAsyncEnumerator <TPage, TState> > queue; if (comparer == null) { queue = new QueueWrapper <PartitionRangePageAsyncEnumerator <TPage, TState> >( new Queue <PartitionRangePageAsyncEnumerator <TPage, TState> >(bufferedEnumerators)); } else { queue = new PriorityQueueWrapper <PartitionRangePageAsyncEnumerator <TPage, TState> >( new PriorityQueue <PartitionRangePageAsyncEnumerator <TPage, TState> >( bufferedEnumerators, comparer)); } return(queue); }); }
public TheMovieDbApi(IMapper mapper, IApi api, ISettingsService <TheMovieDbSettings> settingsService) { Api = api; Mapper = mapper; Settings = new AsyncLazy <TheMovieDbSettings>(() => settingsService.GetSettingsAsync()); }
/// <summary> /// Marks the discovery document as stale and will trigger a request to the discovery endpoint on the next request to get the DiscoveryResponse. /// </summary> public void Refresh() { _lazyResponse = new AsyncLazy <ConsentDiscoveryDocumentResponse>(GetResponseAsync); }
public ChangedStateContext(IResourceMetadata info, IResourceTrackedState lastState, AsyncLazy <T> payload) { EnsureArg.IsNotNull(info); EnsureArg.IsNotNull(payload); Info = info; Payload = payload; LastState = lastState; }
public LocalRepositoryState(IReactiveProcessFactory factory, IRepositoryOrchestration orchestration, IOptions <GitRepositoryOptions> options) { cli = new GitCli(factory, checkoutPath: options.Value.CheckoutPath, repository: options.Value.Repository, userName: options.Value.UserName, userEmail: options.Value.UserEmail); this.remoteBranchesAsync = BuildRemoteBranches(); }
public void RefreshAll() { remoteBranchesAsync = BuildRemoteBranches(); allUpdates.OnNext(Unit.Default); }
/// <summary> /// Provided for unit tests. Expectation is that the default constructor will be called. /// </summary> /// <param name="accountManager">Account manager, most likely a mock</param> /// <param name="interactiveLogin">Interactive login provider most likely a mock</param> public VisualStudioAccountProvider(AsyncLazy <IAccountManager> accountManager, IInteractiveLoginProvider interactiveLogin) { _accountManager = accountManager; _loginProvider = interactiveLogin; Id = $"{typeof(VisualStudioAccountProvider).Name}_{Guid.NewGuid()}"; }
static CommandUiUtilities() { CommandStateCacheInvalidator = new AsyncLazy <IVsInvalidateCachedCommandState>( () => ServiceLocator.GetGlobalServiceFreeThreadedAsync <SVsInvalidateCachedCommandState, IVsInvalidateCachedCommandState>(), NuGetUIThreadHelper.JoinableTaskFactory); }
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); }
public EncapsulateFieldResult(Func <CancellationToken, Task <AbstractEncapsulateFieldService.Result> > resultGetter) { _resultGetter = new AsyncLazy <AbstractEncapsulateFieldService.Result>(c => resultGetter(c), cacheResult: true); }
public async Task <bool> ScheduleRestoreAsync( SolutionRestoreRequest request, CancellationToken token) { if (token.IsCancellationRequested) { return(false); } // Reset to signal that a restore is in progress. // This sets IsBusy to true _isCompleteEvent.Reset(); try { // Initialize if not already done. await InitializeAsync(); var pendingRestore = _pendingRestore; var shouldStartNewBGJobRunner = true; // lock _pendingRequests to figure out if we need to start a new background job for restore // or if there is already one running which will also take care of current request. lock (_lockPendingRequestsObj) { // check if there are already pending restore request or active restore task // then don't initiate a new background job runner. if (_pendingRequests.Value.Count > 0 || IsBusy) { shouldStartNewBGJobRunner = false; } else if (_lockService.Value.IsLockHeld && _lockService.Value.LockCount > 0) { // when restore is not running but NuGet lock is still held for the current async operation, // then it means other NuGet operation like Install or Update are in progress which will // take care of running restore for appropriate projects so skipping auto restore in that case. return(true); } // on-board request onto pending restore operation _pendingRequests.Value.TryAdd(request); } try { using (_joinableCollection.Join()) { // when there is no current background restore job running, then it will start a new one. // else, current requrest will also await the existing job to be completed. if (shouldStartNewBGJobRunner) { _backgroundJobRunner = new AsyncLazy <bool>( () => StartBackgroundJobRunnerAsync(_workerCts.Token), _joinableFactory); } // Await completion of the requested restore operation or // completion of the current job runner. // The caller will be unblocked immediately upon // cancellation request via provided token. return(await await Task .WhenAny( pendingRestore.Task, _backgroundJobRunner.GetValueAsync()) .WithCancellation(token)); } } catch (OperationCanceledException) when(token.IsCancellationRequested) { return(false); } catch (Exception e) { Logger.LogError(e.ToString()); return(false); } } finally { // Signal that all pending operations are complete. _isCompleteEvent.Set(); } }
public PackageSearchMetadataBuilder WithVersions(AsyncLazy <IEnumerable <VersionInfo> > lazyVersionsFactory) { _lazyVersionsFactory = lazyVersionsFactory; return(this); }
private async Task _processEntry(int idx, int total, IResourceMetadata info, ResourceState lastState, CancellationToken ctk = default) { try { _logger.Info("({4}/{5}) Detected change on Resource.Id=\"{0}\", Resource.Modified={1}, OldState.Modified={2}, OldState.Retry={3}. Processing..." , info.ResourceId , info.Modified , lastState?.Modified , lastState?.RetryCount , idx , total ); var sw = Stopwatch.StartNew(); AsyncLazy <T> payload = new AsyncLazy <T>(() => _retrievePayload(info, lastState, ctk)); var state = new ResourceState() { Tenant = _config.Tenant, ResourceId = info.ResourceId, Modified = lastState?.Modified ?? info.Modified, // we want to update modified only on success or Ban or first run LastEvent = SystemClock.Instance.GetCurrentInstant(), RetryCount = lastState?.RetryCount ?? 0, CheckSum = lastState?.CheckSum, RetrievedAt = lastState?.RetrievedAt, Extensions = info.Extensions }; try { await _processResource(new ChangedStateContext <T>(info, lastState, payload), ctk).ConfigureAwait(false); // if handlers retrived data, fetch the result to check the checksum if (payload.IsStarted) { // if the retrievePayload task gone in exception but the _processResource did not ... // here we care only if we have a payload to use if (payload.Task.Status == TaskStatus.RanToCompletion) { var newState = await payload; if (newState != null) { if (!string.IsNullOrWhiteSpace(newState.CheckSum) && state.CheckSum != newState.CheckSum) { _logger.Info("Checksum changed on Resource.Id=\"{0}\" from \"{1}\" to \"{2}\"", state.ResourceId, state.CheckSum, newState.CheckSum); } state.CheckSum = newState.CheckSum; state.RetrievedAt = newState.RetrievedAt; } else // no payload retrived, so no new state. Generally due to a same-checksum { } state.Modified = info.Modified; state.RetryCount = 0; // success } } else // for some reason, no action has been and payload has not been retrieved. We do not change the state { } } catch (Exception ex) { state.LastException = ex; LogLevel lvl = ++state.RetryCount == _config.MaxRetries ? LogLevel.Fatal : LogLevel.Warn; _logger.Log(lvl, ex, "Error while processing ResourceId=\"{0}\"", info.ResourceId); // if we're in BAN and we tried to exit BAN and we failed, update the Modified anw if (state.RetryCount > _config.MaxRetries) { state.Modified = info.Modified; } } await _stateProvider.SaveStateAsync(new[] { state }, ctk).ConfigureAwait(false); _logger.Info("({3}/{4}) ResourceId=\"{0}\" handled {2}successfully in {1}", state.ResourceId, sw.Elapsed, state.RetryCount == 0 ? "" : "not ", idx , total); if (sw.Elapsed > _config.ResourceDurationNotificationLimit) { _logger.Fatal("Processing of ResourceId=\"{0}\" took too much: {1}", state.ResourceId, sw.Elapsed); } } catch (Exception ex) { // chomp it, we'll retry this file next time, forever, fuckit _logger.Error(ex, "({4}/{5}) Error in processing the ResourceId=\"{0}\". The execution will be automatically retried.", info.ResourceId); } }
internal PublishItemsOutputGroupProvider(IProjectAccessor projectAccessor, ConfiguredProject configuredProject, IProjectThreadingService projectThreadingService) { _projectAccessor = projectAccessor; _configuredProject = configuredProject; _outputGroups = new AsyncLazy <IImmutableSet <IOutputGroup> >(GetOutputGroupMetadataAsync, projectThreadingService.JoinableTaskFactory); }
private static void EnsureInitialized() { _liveModel = _liveModel ?? new AsyncLazy <T>(CreateAsync, ThreadHelper.JoinableTaskFactory); _settingsManager = _settingsManager ?? new AsyncLazy <ShellSettingsManager>(GetSettingsManagerAsync, ThreadHelper.JoinableTaskFactory); }
public DotnetTryFixture() { _disposableDirectory = DisposableDirectory.Create(); _lazyReady = new AsyncLazy <bool>(ReadyAsync); }
public GuestTenantController(IRepositoryFactory repositoryFactory) { _guestSessionLazyAsync = new AsyncLazy <IRepository <GuestSession> >(() => repositoryFactory.CreateRepositoryAsync <GuestSession>()); _guestInviteLazyAsync = new AsyncLazy <IRepository <GuestInvite> >(() => repositoryFactory.CreateRepositoryAsync <GuestInvite>()); }
void Init() { // Init the core api inteface. Bitswap = new BitswapApi(this); Block = new BlockApi(this); BlockRepository = new BlockRepositoryApi(this); Bootstrap = new BootstrapApi(this); Config = new ConfigApi(this); Dag = new DagApi(this); Dht = new DhtApi(this); Dns = new DnsApi(this); FileSystem = new FileSystemApi(this); Generic = new GenericApi(this); Key = new KeyApi(this); Name = new NameApi(this); Object = new ObjectApi(this); Pin = new PinApi(this); PubSub = new PubSubApi(this); Stats = new StatsApi(this); Swarm = new SwarmApi(this); // Async properties LocalPeer = new AsyncLazy <Peer>(async() => { log.Debug("Building local peer"); var keyChain = await KeyChain().ConfigureAwait(false); log.Debug("Getting key info about self"); var self = await keyChain.FindKeyByNameAsync("self").ConfigureAwait(false); var localPeer = new Peer { Id = self.Id, PublicKey = await keyChain.GetPublicKeyAsync("self").ConfigureAwait(false), ProtocolVersion = "ipfs/0.1.0" }; var version = typeof(IpfsEngine).GetTypeInfo().Assembly.GetName().Version; localPeer.AgentVersion = $"net-ipfs/{version.Major}.{version.Minor}.{version.Revision}"; log.Debug("Built local peer"); return(localPeer); }); SwarmService = new AsyncLazy <Swarm>(async() => { log.Debug("Building swarm service"); if (Options.Swarm.PrivateNetworkKey == null) { var path = Path.Combine(Options.Repository.Folder, "swarm.key"); if (File.Exists(path)) { using (var x = File.OpenText(path)) { Options.Swarm.PrivateNetworkKey = new PreSharedKey(); Options.Swarm.PrivateNetworkKey.Import(x); } } } var peer = await LocalPeer.ConfigureAwait(false); var keyChain = await KeyChain().ConfigureAwait(false); var self = await keyChain.GetPrivateKeyAsync("self").ConfigureAwait(false); var swarm = new Swarm { LocalPeer = peer, LocalPeerKey = PeerTalk.Cryptography.Key.CreatePrivateKey(self), NetworkProtector = Options.Swarm.PrivateNetworkKey == null ? null : new Psk1Protector { Key = Options.Swarm.PrivateNetworkKey } }; if (Options.Swarm.PrivateNetworkKey != null) { log.Debug($"Private network {Options.Swarm.PrivateNetworkKey.Fingerprint().ToHexString()}"); } log.Debug("Built swarm service"); return(swarm); }); BitswapService = new AsyncLazy <BlockExchange.Bitswap>(async() => { log.Debug("Building bitswap service"); var bitswap = new BlockExchange.Bitswap { Swarm = await SwarmService.ConfigureAwait(false), BlockService = Block }; log.Debug("Built bitswap service"); return(bitswap); }); DhtService = new AsyncLazy <PeerTalk.Routing.Dht1>(async() => { log.Debug("Building DHT service"); var dht = new PeerTalk.Routing.Dht1 { Swarm = await SwarmService.ConfigureAwait(false) }; dht.Swarm.Router = dht; log.Debug("Built DHT service"); return(dht); }); PubSubService = new AsyncLazy <PeerTalk.PubSub.NotificationService>(async() => { log.Debug("Building PubSub service"); var pubsub = new PeerTalk.PubSub.NotificationService { LocalPeer = await LocalPeer.ConfigureAwait(false) }; pubsub.Routers.Add(new PeerTalk.PubSub.FloodRouter { Swarm = await SwarmService.ConfigureAwait(false) }); log.Debug("Built PubSub service"); return(pubsub); }); }
protected async Task SetLastUpdatedVersion(AssetVersion version) { await SetVersion(AppConstants.CacheKeys.lastUpdatedVersion, version); this.lastUpdatedVersion = GetLazyVersion(AppConstants.CacheKeys.lastUpdatedVersion); }
public Analysis(Document document, AsyncLazy <DocumentAnalysisResults> results) { Document = document; Results = results; }
public AzureIdentityResource(string resourceId) : base("Microsoft.ManagedIdentity/userAssignedIdentities", resourceId) { identityInstance = new AsyncLazy <IIdentity>(GetIdentityAsync); }
protected async Task SetPreviousPublishedVersion(AssetVersion version) { await SetVersion(AppConstants.CacheKeys.previouslyPublishedVersion, version); this.previouslyPublishedVersion = GetLazyVersion(AppConstants.CacheKeys.previouslyPublishedVersion); }
public ProjectOutputWindowPaneProvider(IProjectThreadingService threadingService, IVsUIService <SVsOutputWindow, IVsOutputWindow> outputWindow) { _threadingService = threadingService; _outputWindow = outputWindow; _outputWindowPane = new AsyncLazy <IVsOutputWindowPane?>(CreateOutputWindowPaneAsync, threadingService.JoinableTaskFactory); }
public LazyRemoteConnection(RemoteConnectionFactory remoteConnectionFactory) { _connectionTask = new AsyncLazy <RemoteConnection>(() => remoteConnectionFactory.ConnectAsync()); }
public GitHubUserModelService(IGitHubUserClientFactory gitHubUserClientFactory) { _lazyGitHubUserClient = new AsyncLazy <IGitHubClient>(() => gitHubUserClientFactory.CreateClient()); _lazyGitHubUserGraphQLClient = new AsyncLazy <IGitHubGraphQLClient>(() => gitHubUserClientFactory.CreateGraphQLClient()); }
public VisualStudioRemoteHostClientProvider(HostWorkspaceServices services) { _services = services; _lazyClient = new AsyncLazy <RemoteHostClient>(CreateHostClientAsync, cacheResult: true); }
static SomeClass() { Cache = new AsyncLazy <Dictionary <string, TItem> >(GetCacheAsync); }
public WaitThatValidatesInvariants(AsyncLazy <T> asyncLazy) => _asyncLazy = asyncLazy;