Exemplo n.º 1
0
        internal static async Task <ThreadRental> CreateAsync(SyncContextAdapter syncContextAdapter, ITestMethod testMethod)
        {
            var disposalTaskSource = new TaskCompletionSource <object?>();
            var syncContextSource  = new TaskCompletionSource <SynchronizationContext>();
            var thread             = new Thread(() =>
            {
                var uiSyncContext = syncContextAdapter.Create();
                if (syncContextAdapter.ShouldSetAsCurrent)
                {
                    SynchronizationContext.SetSynchronizationContext(uiSyncContext);
                }

                syncContextAdapter.InitializeThread();
                syncContextSource.SetResult(uiSyncContext);
                syncContextAdapter.PumpTill(uiSyncContext, disposalTaskSource.Task);
            });

            thread.Name = $"{testMethod.TestClass.Class.Name}.{testMethod.Method.Name}";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                thread.SetApartmentState(ApartmentState.STA);
            }

            thread.Start();

            var syncContext = await syncContextSource.Task.ConfigureAwait(false);

            var rental = new ThreadRental(
                syncContextAdapter,
                disposalTaskSource,
                syncContext);

            return(rental);
        }