本文整理汇总了C#中AsyncLazy类的典型用法代码示例。如果您正苦于以下问题:C# AsyncLazy类的具体用法?C# AsyncLazy怎么用?C# AsyncLazy使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AsyncLazy类属于命名空间,在下文中一共展示了AsyncLazy类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: RemoteHostClientService
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);
}
开发者ID:XieShuquan,项目名称:roslyn,代码行数:11,代码来源:DefaultRemoteHostClientServiceFactory.RemoteHostClientService.cs
示例17: Must_initialize_only_once
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));
}
开发者ID:nathan-alden,项目名称:junior-common,代码行数:12,代码来源:AsyncLazyTester.cs
示例18: AsyncLazy_AwaitReturnsFuncValue
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);
}
开发者ID:robertoenbarcelona,项目名称:code-challenge-3,代码行数:12,代码来源:AsynsLazyFixture.cs
示例19: AsyncLazy_NeverAwaitedDoesNotCallFunc
public void AsyncLazy_NeverAwaitedDoesNotCallFunc()
{
//Arrange
Func<int> func = () =>
{
Assert.Fail();
return A.Dummy<int>();
};
//Assert
var lazy = new AsyncLazy<int>(func);
}
开发者ID:robertoenbarcelona,项目名称:code-challenge-3,代码行数:12,代码来源:AsynsLazyFixture.cs
示例20: FuzzyFindAsync
/// <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;
}
开发者ID:peter76111,项目名称:roslyn,代码行数:16,代码来源:SymbolTreeInfo.cs
注:本文中的AsyncLazy类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论