1

I have an ASP.NET Core 5.0 application where I am integrating a WPF component. The component renders a chart. The issue is that WPF requires STA (Single Thread Apartment). The thread pool used by ASP.NET is MTA. That leads to the exception:

The calling thread must be STA, because many UI components require this

I know there are a lot of workarounds available like the following:

    public static Task<T> RunThreadWithSTA<T>(Func<T> f)
    {
        var completionSource = new TaskCompletionSource<T>();
        var thread = new Thread(() =>
        {
            try
            {
                completionSource.SetResult(f());
            }
            catch (Exception e)
            {
                completionSource.SetException(e);
            }
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        return completionSource.Task;
    }

It works fine (for sync code, but not async code). However this takes away threads from ASP.NET as is considered bad practice.

Other methods (from 10 years ago) have also been suggested, like a custom STA Thread Pool, see Can the WPF API be safely used in a WCF service? but I am not very inclined towarding changing the thread-pool.

So as far as I can see there is no suggested method of handling this.

  • 1
    *However this takes away threads from ASP.NET as is considered bad practice.* ... well, it is not worse practie than using WPF in ASP.NET server code ... so here is the problem ... suggestion: do not use WPF at all find library for generating charts without dependency to WPF/ dedicated for ASP.NET Core – Selvin Feb 03 '21 at 15:19
  • I am not sure that the `RunThreadWithSTA` takes away threads from ASP.NET. It creates a dedicated STA thread. It doesn't borrow threads from the `ThreadPool` that serves is a pool of workers for ASP.NET requests. I would be more concerned about how much CPU-hungry is this WPF integration, and I would ask how many STA threads you expect to have running concurrently at maximum. – Theodor Zoulias Feb 03 '21 at 15:23
  • Thanks for your comments, you are right RunThreadWithSTA does not take them out of the ThreadPool, but it still takes them from the same process. I guess it's not really an issue as this is not a performance critical application. @Selvin, I am kind of stuck with it, I am using SciChart... – user1832348 Feb 03 '21 at 15:34

0 Answers0