【问题标题】:ThreadStatic in asynchronous ASP.NET Web API异步 ASP.NET Web API 中的 ThreadStatic
【发布时间】:2017-07-19 07:46:23
【问题描述】:

是否有可能在单个请求中使用线程静态变量?当前代码使用线程静态变量进行日志记录,现在我们想使用异步控制器方法(带有异步和等待模式),这会导致问题,因为当打开新线程时变量为空。

【问题讨论】:

    标签: asp.net asp.net-web-api async-await threadstatic requestscope


    【解决方案1】:

    await会导致线程跳转,所以线程静态变量自然会出问题。

    要解决此问题,您可以使用AsyncLocal<T>(在 .NET 4.6 中可用)或(如果必须)HttpContext.Current.Items。在这两个中,我肯定会推荐 AsyncLocal<T> 而不是 Items,如果它在您的平台上可用。

    【讨论】:

    • 我能问你为什么推荐 AsyncLocal 而不是 Items 吗?
    • 我推荐AsyncLocal<T> 而不是HttpContext.Current,因为HttpContext.Current 被认为是糟糕的设计,已在 ASP.NET Core 中删除。
    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多