本文整理汇总了C#中AsyncLazy.GetValueAsync方法的典型用法代码示例。如果您正苦于以下问题:C# AsyncLazy.GetValueAsync方法的具体用法?C# AsyncLazy.GetValueAsync怎么用?C# AsyncLazy.GetValueAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类AsyncLazy
的用法示例。
在下文中一共展示了AsyncLazy.GetValueAsync方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例2: SynchronousContinuationsDoNotRunWithinGetValueCallCore
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);
}
示例3: CancellationDuringInlinedComputationFromGetValueAsyncStillCachesResult
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);
}
}
示例4: FindAsync
/// <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;
}
示例5: FindAsync
/// <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(); ;
}
示例6: GetValueAsyncThatIsCancelledReturnsTaskCancelledWithCorrectToken
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);
}
}