Mrc*_*ief 3 c# asp.net apartment-state asp.net-web-api asp.net-web-api2
这篇文章让 WebApi无法在STA模式下运行.但这篇文章也是2岁.
我一直在挖掘新的WebApi2,但似乎无法找到MessageHandlers在STA模式下运行的方法.
那么有没有人找到在STA模式下运行WebApi或WebApi2的方法?
因此,如果您想将整个请求处理线程切换到STA模式,那么您最好使用MVC.但是,如果您的处理程序执行一个不涉及将整个线程切换到STA模式的一次性任务,那么Web API使它非常简单.我是这样做的:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
需要考虑的事项:
StaTaskScheduler很重要.考虑将其移动到单个或确保在App_Start期间仅初始化一次| 归档时间: |
|
| 查看次数: |
986 次 |
| 最近记录: |