當前位置: 首頁>>代碼示例>>C#>>正文


C# AsyncLazy類代碼示例

本文整理匯總了C#中AsyncLazy的典型用法代碼示例。如果您正苦於以下問題:C# AsyncLazy類的具體用法?C# AsyncLazy怎麽用?C# AsyncLazy使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AsyncLazy類屬於命名空間,在下文中一共展示了AsyncLazy類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: MsBuildMap

        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;
            });
        }
開發者ID:perpetual-motion,項目名稱:clrplus,代碼行數:29,代碼來源:MsBuildMap.cs

示例2: ProjectState

        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);
        }
開發者ID:GuilhermeSa,項目名稱:roslyn,代碼行數:26,代碼來源:ProjectState.cs

示例3: AsyncLazy_MultipleAwaitersOnlyInvokeFuncOnce

        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);
        }
開發者ID:robertoenbarcelona,項目名稱:code-challenge-3,代碼行數:27,代碼來源:AsynsLazyFixture.cs

示例4: ProjectState

        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);
        }
開發者ID:SoumikMukherjeeDOTNET,項目名稱:roslyn,代碼行數:30,代碼來源:ProjectState.cs

示例5: TestSyntaxTreeFactoryService

        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());
        }
開發者ID:riversky,項目名稱:roslyn,代碼行數:31,代碼來源:SyntaxTreeFactoryServiceTests.cs

示例6: FindAsync

 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);
 }
開發者ID:Rickinio,項目名稱:roslyn,代碼行數:7,代碼來源:SymbolTreeInfo.cs

示例7: AsyncLazy_Await_ReturnsFuncValue

        public async Task AsyncLazy_Await_ReturnsFuncValue()
        {
            Func<int> func = () => 13;
            var lazy = new AsyncLazy<int>(func);

            var result = await lazy;
            Assert.AreEqual(13, result);
        }
開發者ID:Knight1988,項目名稱:SharpUtility,代碼行數:8,代碼來源:AsyncLazyTest.cs

示例8: Usage

 public Usage()
 {
     sharedResource = new AsyncLazy<int>(async () =>
     {
         await Task.Delay(1000);
         return 13;
     });
 }
開發者ID:CarbineCoder,項目名稱:Presentations,代碼行數:8,代碼來源:Usage.cs

示例9: AzureLocation

        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();
            }
        }
開發者ID:roomaroo,項目名稱:coapp.powershell,代碼行數:58,代碼來源:AzureLocation.cs

示例10: LazyRemoteService

 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;
 }
開發者ID:GloryChou,項目名稱:roslyn,代碼行數:9,代碼來源:InteractiveHost.LazyRemoteService.cs

示例11: SynchronousRequestShouldCacheValueWithAsynchronousComputeFunction

        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);
        }
開發者ID:Rickinio,項目名稱:roslyn,代碼行數:9,代碼來源:AsyncLazyTests.cs

示例12: LoadAsync

 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);
 }
開發者ID:korzenikov,項目名稱:Projects,代碼行數:10,代碼來源:AsyncLazyBasedLoader.cs

示例13: GetValueAsyncReturnsCompletedTaskIfAsyncComputationCompletesImmediately

 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);
 }
開發者ID:elemk0vv,項目名稱:roslyn-1,代碼行數:10,代碼來源:AsyncLazyTests.cs

示例14: AsyncLazy_NeverAwaited_DoesNotCallFunc

        public void AsyncLazy_NeverAwaited_DoesNotCallFunc()
        {
            Func<int> func = () =>
            {
                Assert.Fail();
                return 13;
            };

            var lazy = new AsyncLazy<int>(func);
        }
開發者ID:Knight1988,項目名稱:SharpUtility,代碼行數:10,代碼來源:AsyncLazyTest.cs

示例15: RethinkDBClient

        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();
            } );
        }
開發者ID:robzhu,項目名稱:Library.WebApi,代碼行數:10,代碼來源:RethinkDBClient.cs


注:本文中的AsyncLazy類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。