问题
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