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.