C#:在并行线程中设置 HttpContext.Current 有什么问题吗?

发布于 2024-12-11 00:09:19 字数 472 浏览 0 评论 0原文

我正在使用一个依赖于 HttpContext.Current 的库。该库是 Facebook C# SDK,但我的问题也应该适用于其他场景。我想从并行线程内部使用这个库。但是, HttpContext.Current 在并行线程中不可用,因此我正在考虑将其缓存到本地变量,然后在并行线程中设置它,如下所示:

var httpContext = HttpContext.Current;
Parallel.ForEach(items, item => {

    try {

        HttpContext.Current = httpContext;

        // Call a method that relies on HttpContext.Current

    } finally {
        HttpContext.Current = null;
    }
});

您预见到这有什么问题吗?这样做有什么后果吗?

I'm using a library that relies on HttpContext.Current. The library is Facebook C# SDK, but my question should apply in other scenarios as well. I'd like to use this library from inside of a parallel thread. However, HttpContext.Current is not available in the parallel thread, so I'm thinking about caching it to a local variable and then setting it in the parallel thread like this:

var httpContext = HttpContext.Current;
Parallel.ForEach(items, item => {

    try {

        HttpContext.Current = httpContext;

        // Call a method that relies on HttpContext.Current

    } finally {
        HttpContext.Current = null;
    }
});

Do you foresee anything wrong with this? Are there any repercussions to doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲世九天 2024-12-18 00:09:19

对我来说似乎还可以。使用 try ...finally 也是一个好点,因为线程可以重用,并且可以使上下文长时间保持活动状态,避免垃圾收集。
不要认为还有其他方法可以解决这个问题。

但请注意,您调用的 api 不会在此多线程环境中产生问题。
并非所有执行涉及写入/读取某些缓存值的写入操作或读取操作的代码都是线程安全的。

还要小心,如果字段值不是易失性的或者未使用 System.Threading.Interlocked,则字段值无法正确和/或及时地从一个线程传播到另一个线程!
这可能会给您带来问题,尤其是在发布版本中。

但是,您可以使用 Thread.MemoryBarrier 或锁定,在网络上搜索这个烦人(但不可避免)的问题。

For me seems ok. The use of try ... finally is a good point too because thread can be reused and you can keep the context alive for long times, avoiding garbage collection.
Don't think there is another way to solve this.

Be careful however that the api you are calling does not create problems in this multithreading environment.
Not all code is thread safe performing write operations or read operations that involve writing\reading some cached value.

Be careful also that field values can not be propagated correctly and\or in time from one thread to another if they are not volatile or if System.Threading.Interlocked is not used!
This may create you problems, especially in release builds.

You can however use Thread.MemoryBarrier or lock, search on the web for this annoying (but inevitable) issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文