Skip to content

async test + Apartment(ApartmentState.STA) => await not returning on STA thread #1200

Closed

Description

@yar-shukan

There is the old post on SO:
http://stackoverflow.com/questions/18838116/nunit-async-test-requiressta-await-not-returning-on-sta-thread
It seems like this issue has been there long time ago, but we faced it only after upgrading to NUnit 3.0.1.

We have tests that use async/await with Apartment(ApartmentState.STA) and before the upgrade to NUnit 3.0.1 they used to work, but after the upgrade they fail because WPF components don't run on STA thread after await statement.

Activity

  1. rprouse commented on Apr 7, 2016

    @rprouse
    Member

    Are you saying that when the test is marked STA, the thread is no longer STA after an await in NUnit 3, or are you saying that the workarounds in the SO post no longer work?

  2. yar-shukan commented on Apr 21, 2016

    @yar-shukan
    Author

    Yes, it is no longer STA after await in NUnit 3.2.1 (the same issue in 3.0.1 as well).
    Marking test method with [Apartment(ApartmentState.STA)] as well as obsolete [RequiresSTA] doesn't work. The managed thread ID is different after await.

  3. keithallenjackson commented on Mar 22, 2017

    @keithallenjackson

    My current work project has ran into this very issue. I'm curious if any work has been done to address this. I'm interested in at least looking into it, but wanted to touch base and get a status update to not duplicate work effort.

  4. Rincoln commented on Jun 29, 2017

    @Rincoln

    I've had to do the same thing to work with proprietary ODBC drivers. My solution is a little convoluted, but works.

    public Task<T> RunSTAThread<T>(Func<T> action)
    {
    var tcs = new TaskCompletionSource<T>();
    System.Threading.Thread runThread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
    {
    try
    {
    var result = action();
    tcs.TrySetResult(result);
    }
    catch (Exception ex)
    {
    tcs.TrySetException(ex);
    }
    }));
    runThread.SetApartmentState(System.Threading.ApartmentState.STA);
    runThread.Start();
    return tcs.Task;
    }

    Then you simply run your method requiring STA thread by:

    var result = await RunSTAThread(MethodRequiringSTA);

  5. CharliePoole commented on Jun 29, 2017

    @CharliePoole
    Member

    This was still marked as confirm and nothing has been done. I guess we should at least consider it confirmed.

  6. jnm2 commented on Jun 29, 2017

    @jnm2
    Contributor

    There's an easy fix for this, I just did this the other day. We need to set a synchronization context and message pump on the STA thread. Otherwise, await schedules continuations on a random thread pool thread.

  7. jnm2 commented on Jun 29, 2017

    @jnm2
    Contributor
  8. jnm2 commented on Jun 29, 2017

    @jnm2
    Contributor

    Here's a workaround you all can use so that you don't waste threads:

    Change

    [Apartment(ApartmentState.STA)]
    public async Task MyTestAsync()
    {
        await FirstThing;
        // Still on STA thread
        await SecondThing;
        // etc
    }

    to

    [Apartment(ApartmentState.STA)]
    public void MyTest()
    {
        SingleThreadedSynchronizationContext.Await(async () =>
        {
            await FirstThing;
            // Still on STA thread
            await SecondThing;
            // etc
        });
    }

    And use:

    public sealed class SingleThreadedSynchronizationContext : SynchronizationContext
    {
        private readonly BlockingCollection<(SendOrPostCallback d, object state)> queue = new BlockingCollection<(SendOrPostCallback, object)>();
    
        public override void Post(SendOrPostCallback d, object state)
        {
            queue.Add((d, state));
        }
    
        public static void Await(Func<Task> taskinvoker)
        {
            var originalContext = Current;
            try
            {
                var context = new SingleThreadedSynchronizationContext();
                SetSynchronizationContext(context);
    
                var task = taskinvoker.Invoke();
                task.ContinueWith(_ => context.queue.CompleteAdding());
    
                while (context.queue.TryTake(out var work, Timeout.Infinite))
                    work.d.Invoke(work.state);
    
                task.GetAwaiter().GetResult();
            }
            finally
            {
                SetSynchronizationContext(originalContext);
            }
        }
    }
  9. jnm2 commented on Jun 29, 2017

    @jnm2
    Contributor

    @nunit/framework-team The fix for this in NUnit will be to install the SingleThreadedSynchronizationContext before each invocation of a test method. This will collide with my PR #2181 so I should probably assign this to myself.

  10. CharliePoole commented on Jun 29, 2017

    @CharliePoole
    Member

    Cool!

  11. self-assigned this
    on Jun 29, 2017
  12. jnm2 commented on Jun 29, 2017

    @jnm2
    Contributor

    (I've been using this for my console apps because sometimes jumping around a bunch of threads gets on my nerves 😛)

  13. added this to the 3.11 milestone on May 14, 2018
  14. jnm2 commented on May 14, 2018

    @jnm2
    Contributor

    This is fixed for 3.11! 🎉

  15. mlimber commented on Feb 15, 2019

    @mlimber

    @jnm2: Is there anything that needs to be done to take advantage of this in 3.11 for a test like:

    [Test]
    public async Task TestDeletion() 
    { 
        // ... assemble here ... 
        await _viewModel.DeleteSelectedObjectsCommand.ExecuteAsync( null ); 
        // ... asserts here ... 
    }
  16. jnm2 commented on Feb 15, 2019

    @jnm2
    Contributor

    @mlimber No, just make sure [Apartment(ApartmentState.STA)] is specified for the method, class (or base class) or assembly. Some runners default to STA, others don't.

    If you're curious, see https://github.com/nunit/nunit/blob/v3.11/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs#L113 and https://github.com/nunit/nunit/blob/v3.11/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs#L30.

    This sets a single-threaded SynchronizationContext so that the task's awaiter posts the continuation back to a queue on the same thread, so it might go without saying, but don't do .ConfigureAwait(false) if you care what thread you continue on.

  17. apobekiaris commented on Jan 23, 2021

    @apobekiaris

    for me the next test fails

            [Test][Apartment(ApartmentState.STA)]
            public async Task Synchronize_styles_when_document_modified(){
                using var richEditDocumentServer = new RichEditDocumentServer();
                await Task.CompletedTask;
                
            }

    however this pass

            [Test][Apartment(ApartmentState.STA)]
            public void Synchronize_styles_when_document_modified(){
                
                SingleThreadedSynchronizationContext.Await(async () =>
                {
                    using var richEditDocumentServer = new RichEditDocumentServer();
                    await Task.CompletedTask;
                });
            }

    I thought it was fixed in 3.11?? and I currently on 3.13

  18. Steinblock commented on Mar 24, 2022

    @Steinblock

    This was I trap I ran into, too.

    To understand it you must know, that behind the scenes something like this happens

    [STAThread] // autogenerated
    public static void Main()
    {
        // STA
        MainAsync().GetAwaiter().GetResult();
    }
    
    private static async Task MainAsync()
    {
        // MTA
    }
    

    So the code in fact behaves like expected.

    I solved it this way

    
        static class Program
        {
            [STAThread]
            async static Task Main()
            {
                await MyInitFunctionAsync();
                await Task.Factory.StartNew(() =>
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }, ApartmentState.STA);
                // code here runs after form1 closes
            }
        }
    
        public static class TaskExtensions
        {
    
            public static Task StartNew(this TaskFactory t, Action action, ApartmentState state)
            {
                var tcs = new TaskCompletionSource<bool>();
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        action();
                        tcs.SetResult(true);
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                });
                thread.IsBackground = false;
                thread.SetApartmentState(state);
                thread.Start();
                return tcs.Task;
            }
    
        }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions