asp.net - 网络API : DelegatingHandler and ApiController on the same thread?

标签 asp.net multithreading asp.net-web-api

在 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/

相关文章:

c# - 使用 .NET 4 的 ASP.NET 是否更快

java - tomcat中的UncaughtExceptionHandler

c# - 从BackgroundWorker线程更新图像UI属性

c# - ReadAsAsync 从 Json 数据中获取空值?

c# - Web API 2.0 IHttpActionResult 缓存

c# - 使用 WebAPI 的 Microsoft Unity 依赖注入(inject)

c# - 使用 C# 创建 MS Access 数据库时命名空间是什么

asp.net - 使用 Windows Sqlite 库和 .NET sqlite 库有什么区别?

asp.net - asp.net 成员(member)登录控件的模板或 css 外观?

java - map 的封装实现