asp.net – “HttpContext.Current”属性和相关事物的交叉线程使用

前端之家收集整理的这篇文章主要介绍了asp.net – “HttpContext.Current”属性和相关事物的交叉线程使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从&基本ASP.NET与C#中的示例>下面的语句:

Another useful property to know about is the static Current property
of the HttpContext class. This property always points to the current
instance of the HttpContext class for the request being serviced. This
can be convenient if you are writing helper classes that will be used
from pages or other pipeline classes and may need to access the
context for whatever reason. By using the static Current property to
retrieve the context,you can avoid passing a reference to it to
helper classes. For example,the class shown in Listing 4-1 uses the
Current property of the context to access the QueryString and print
something to the current response buffer. Note that for this static
property to be correctly initialized,the caller must be executing on
the original request thread,so if you have spawned additional threads
to perform work during a request,you must take care to provide access
to the context class yourself.

我想知道大胆部分的根本原因,一件事导致另一个,这里是我的想法:

We know that a process can have multiple threads. Each of these threads have their own stacks,respectively. These threads also have access to a shared memory area,the heap.

The stack then,as I understand it,is kind of where all the context for that thread is stored. For a thread to access something in the heap it must use a pointer,and the pointer is stored on its stack.

So when we make some cross-thread calls,we must make sure that all the necessary context info is passed from the caller thread’s stack to the callee thread’s stack.

但我不太确定如果我犯了任何错误

任何评论将深表谢意。

谢谢。

这里的堆栈限制为用户堆栈。

解决方法

有四件事情一起工作,导致你正在问的行为:

> HttpContext是一个实例对象,它的引用可以在HttpContext.Current中找到
> Thread也是一个实例对象,它的引用可以在Thread.CurrentThread中找到
> Thread.CurrentThread是静态的,但在每个线程中引用不同的Thread对象
> HttpContext.Current实际上指向Thread.CurrentThread.ExecutionContext.IllogicalCallContext.HostContext

结论我们可以从上面的动词:

>因为HttpContext是一个实例对象而不是静态的,我们需要它的引用来访问它
>因为HttpContext.Current实际上指向一个属性Thread.CurrentThread,改变Thread.CurrentThread到一个不同的对象可能会改变HttpContext.Current
>因为Thread.CurrentThread’切换线程时更改,HttpContext.Current也在切换线程时更改(在这种情况下HttpContext.Current变为null)。

把这一切,在什么原因HttpContext.Current不工作在一个新的线程? Thread.CurrentThread引用更改,发生在切换线程时,更改HttpContext.Current引用,这将阻止我们到达我们想要的HttpContext实例。

要重申,这里唯一神奇的事情是Thread.CurrentThread引用每个Thread中不同的对象。 HttpContext就像任何其他实例对象一样工作。由于同一AppDomain中的线程可以引用相同的对象,所以我们要做的就是将HttpContext的引用传递给我们的新线程。没有要加载的上下文信息或类似的东西。 (有一些相当严重的潜在问题,绕过HttpContext到其他线程,但没有任何东西阻止你这样做)。

我在研究过程中遇到的几个最后一个副词:

>在某些情况下,线程的ExecutionContext被“流”(复制)从一个线程到另一个线程。为什么HttpContext不会“流”到我们的新线程?因为HttpContext不实现ILogicalThreadAffinative接口。存储在ExecutionContext中的类只有在实现了ILogicalThreadAffinative的情况下才会流动。> ASP.NET如何移动HttpContext从线程到线程(线程敏捷)如果没有流?我不完全确定,但它看起来可能会通过它在HttpApplication.OnThreadEnter()。

原文链接:https://www.f2er.com/aspnet/254831.html

猜你在找的asp.Net相关文章