Task and STA / MTA Threading Model RRS feed

  • Question

  • Hi,

    in our Outlook integration (Managed COM AddIn C#) we are using Tasks to execute some work in the background.

    Well, on machines from one of our customers we receive the following exception, when one of our Dialogs is opened in Outlook.

    Beim aufrufenden Thread muss es sich um einen STA-Thread handeln, da dies für viele Komponenten der Benutzeroberfläche erforderlich ist. (my translation: The calling Thread must be a STA-Thread, because this is required for some UI components)
       bei System.Windows.Input.InputManager..ctor()
       bei System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
       bei PresenceProfiles.<OnIsVisibleChanged>d__1.MoveNext()
    --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
       bei System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
       bei System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
       bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       bei System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
       bei System.Threading.ThreadPoolWorkQueue.Dispatch()
       bei System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

    I think, that the problem is, that after a Task is finished, the following instructions are not executed in Outlooks main thread context. How do I force, that the instructions, that are executed after a task is finished are executed in the main thread context.

    Best regards

    Thursday, November 2, 2017 7:16 AM

All replies

  • This boils down to the awaiter configuration. You didn't post how you're calling that task so we're completely guessing here. For this discussion, it is assumed that your addin is starting the task in response to a UI event so the calling code is the UI thread. If this is not true then the problem is completely different.

    When you start a task it'll run on an arbitrary thread. If you're using the async/await pattern then anything after that await will be running back on the UI thread. You don't need to do anything.

    async Task SomeUIMethodAsync ()
       //Running on UI thread (assumption)
       //Wait for the worker thread to complete
       await DoSomethingInTaskAsync();
       //Back on UI thread because you didn't configure the awaiter   

    But if you're creating the task explicitly then you need to tell the scheduler to run the continuation (which I assume you have) on the calling thread.

    void SomeUIWork ()
       //Capture the current sync context
       var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
       //Not using async here...
       var task = Task.Run(() => DoWorkOnTask())
                      .ContinueWith(() => DoMoreWorkOntask())
                      .ContinueWith(() => DoUIWork(), scheduler);

    Michael Taylor

    Thursday, November 2, 2017 2:04 PM
  • Hi Michael,

    thanks for your help.

    Well, I think that the reason for the problem is a false usage of async/await in the underlying code.

    I am just inspecting the code.

    Best regards,

    Friday, November 3, 2017 9:06 AM

  • Hi  ChristianHavelDE,

    thanks for posting here.

    If your problem is solved you can close the thread by marking helpful posts as an answer. This will help other members to find the solution quickly if they have faced the similar issue.

    Your understanding and cooperation will be grateful.

    Best Regards,

    Yohann Lu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Monday, November 6, 2017 7:15 AM
  • Hi,

    I meet a 'System.Threading.ThreadStateException' in System.Windows.Forms.dll due to a lack of STA, Single-Threaded Apartment. My main app has the [STAThread] attribute but some components are updated from threads.

    foreach (Control c in Steps)
      await Task.Run(() => Update(c));

    I suppose I would need to set the shceduler, but it's not provided in the `Run` method.

    How I'm meant to implement this?


    Wednesday, May 6, 2020 11:45 AM
  • Please do not respond to 3 year old threads about your issues. Post your own question and reference earlier posts if necessary.

    Michael Taylor

    Thursday, May 7, 2020 4:09 AM