在 WebAPI 自托管应用程序中,DelegatingHandler 的 SendAsync() 方法和 ApiController 的任何方法是否始终在同一线程上执行?
使用 [ThreadStatic] 变量将 RequestId 从 SessionHandler 传递到 TestController 是否安全?
示例:
public class TestController : ApiController
{
[HttpGet]
public string Run()
{
LogManager.GetLogger("Controller").InfoFormat("Thread id: {0} ", Thread.CurrentThread.ManagedThreadId);
return "Bar";
}
}
public class SessionHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LogManager.GetLogger("SessionHandler").InfoFormat("Thread id: {0} ", Thread.CurrentThread.ManagedThreadId);
return await base.SendAsync(request, cancellationToken);
}
}
最佳答案
In a WebAPI Self-Host application, will SendAsync() method of DelegatingHandler and any method of ApiController always execute on the same thread?
Is it safe to use [ThreadStatic] variable to pass RequestId from SessionHandler to TestController ?
不,不。 WebAPI 上的 async
将线程返回到运行时,因此管道中的任何异步( Controller 操作、过滤器等)都可以在另一个线程上恢复。
关于asp.net - 网络API : DelegatingHandler and ApiController on the same thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813429/