本文整理汇总了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;
});
}
示例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);
}
示例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);
}
示例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);
}
示例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());
}
示例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);
}
示例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);
}
示例8: Usage
public Usage()
{
sharedResource = new AsyncLazy<int>(async () =>
{
await Task.Delay(1000);
return 13;
});
}
示例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();
}
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
示例14: AsyncLazy_NeverAwaited_DoesNotCallFunc
public void AsyncLazy_NeverAwaited_DoesNotCallFunc()
{
Func<int> func = () =>
{
Assert.Fail();
return 13;
};
var lazy = new AsyncLazy<int>(func);
}
示例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();
} );
}