Reputation: 76238
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?
Upvotes: 3
Views: 1384
Reputation: 76238
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:
StaTaskScheduler
is heavy. Consider moving it to a singleton or ensure it is initialized only once during App_StartUpvotes: 6