Search code examples
c#asp.netasp.net-web-apiasp.net-web-api2apartment-state

ASP.Net WebApi STA Mode


This post scratches off WebApi from being able to run in STA mode. But this post is also 2 years old.

I've been digging into the newer WebApi2 but can't seem to find a way to make MessageHandlers run in STA mode.

So has anyone found a way of running WebApi or WebApi2 in STA mode?


Solution

  • So it seems that if you want to switch the entire request processing thread to STA mode, you're better off with MVC. However, if your handler does a one off task that doesn't involve switching the entire thread into STA mode, Web API makes it pretty easy. Here's how I did it:

    public class StaHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // consider moving it to singleton instance to improve performance
            var staTaskScheduler = new StaTaskScheduler(100);
    
            return Task.Factory.StartNew<HttpResponseMessage>(() =>
            {
                //somethign that does its magic and returns a HttpResponseMessag
                return new HttpResponseMessage();
            }, cancellationToken,
                TaskCreationOptions.None,
                staTaskScheduler);
        }
    }
    

    Things to consider:

    • Creating StaTaskScheduler is heavy. Consider moving it to a singleton or ensure it is initialized only once during App_Start
    • Thread Pool Size (100 in my example) can also play a role in how well this scales. Unfortunately, there is no magic formula to get this right. I created Web Performance Load Tests to figure out a sweet spot on my servers.