C#:任何问题的并行线程设置HttpContext.Current? [英] C#: Anything wrong with setting HttpContext.Current in a parallel thread?

查看:558
本文介绍了C#:任何问题的并行线程设置HttpContext.Current?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是依赖于HttpContext.Current库。图书馆是Facebook的C#SDK,但我的问题应在其他情况下也适用。我想使用这个库从并行线程内。然而,HttpContext.Current是不是在并行线程可用的,所以我想它缓存到本地变量,然后将它设置在平行螺纹是这样的:

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?

推荐答案

对于我来说似乎确定。使用try ...总算是好点,因为过多的线程可以重复使用,你可以保持的背景下存活时间长,避免了垃圾收集。
不要以为还有另一种方式来解决这个问题。

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.

不过要小心,你是叫不建立在这个多线程的环境问题的API。
并非所有code是线程安全的执行写入操作或读取涉及编写\\读一些缓存值的操作。

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.

小心也是字段值不能正确和\\或在时间上从一个线程,如果他们不挥发性传播到另一个,或者如果不使用System.Threading.Interlocked!
这可能会造成你的问题,尤其是在发布版本。

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.

您可以使用,无论Thread.MemoryBarrier或锁定,在网上搜索这恼人的(而且是不可避免的)问题上。

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

这篇关于C#:任何问题的并行线程设置HttpContext.Current?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆