C#: Anything wrong with setting HttpContext.Current in a parallel thread?

纵饮孤独 提交于 2019-12-19 03:07:42

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7851532/c-anything-wrong-with-setting-httpcontext-current-in-a-parallel-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!