private static async Task AssertUsesSynchronizationContext(int arity, bool?configureAwait, bool shouldUseSynchronizationContext)
        {
            var source = new TaskCompletionSource <object>();

            var adapters = AwaiterAdapter.CreateAdapters(Enumerable.Repeat(source.Task, arity).ToArray(), continueOnCapturedContext: configureAwait);

            var copyableContext = new CopyableSynchronizationContext();

            using (TempSyncContext(copyableContext))
            {
                var resultSourcesByAdapterIndex = adapters.Select(_ => new TaskCompletionSource <SynchronizationContext>()).ToArray();

                for (var i = 0; i < adapters.Count; i++)
                {
                    var adapterIndex = i;
                    adapters[i].OnCompleted(() => resultSourcesByAdapterIndex[adapterIndex].SetResult(SynchronizationContext.Current));
                }

                source.SetResult(null);

                var resultsByAdapterIndex = await Task.WhenAll(resultSourcesByAdapterIndex.Select(s => s.Task));

                var expected = shouldUseSynchronizationContext ? copyableContext : null;

                Assert.All(
                    adapters.Zip(resultsByAdapterIndex, (adapter, result) => (Adapter: adapter, Result: result)),
                    r => Assert.Same(expected, r.Result));
            }
        }
예제 #2
0
        private static void AssertUsesSynchronizationContext(int arity, bool?configureAwait, bool shouldUseSynchronizationContext)
        {
            var source = new TaskCompletionSource <object>();

            var adapters = AwaiterAdapter.CreateAdapters(Enumerable.Repeat(source.Task, arity).ToArray(), continueOnCapturedContext: configureAwait);

            var copyableContext = new CopyableSynchronizationContext();

            using (TempSyncContext(copyableContext))
            {
                var actualContinuationContextByAdapterIndex = new SynchronizationContext[adapters.Count];

                for (var i = 0; i < adapters.Count; i++)
                {
                    var adapterIndex = i;
                    adapters[i].OnCompleted(() => actualContinuationContextByAdapterIndex[adapterIndex] = SynchronizationContext.Current);
                }

                source.SetResult(null);

                for (var i = 0; i < adapters.Count; i++)
                {
                    if (shouldUseSynchronizationContext)
                    {
                        Assert.Same(expected: copyableContext, actual: actualContinuationContextByAdapterIndex[i]);
                    }
                    else
                    {
                        Assert.Null(actualContinuationContextByAdapterIndex[i]);
                    }
                }
            }
        }