当前位置:网站首页>ASP. Net core - Safety of asynclocal in asp NET Core
ASP. Net core - Safety of asynclocal in asp NET Core
2022-06-25 06:35:00 【javail】
problem :
For .NET Core, AsyncLocal is the replacement for CallContext . about .NET Core, AsyncLocal yes CallContext substitute .However, it is unclear how "safe" it is to use in ASP.NET Core. however , It is not clear where ASP.NET Core Use it in “ Security ” how .
In ASP.NET 4 (MVC 5) and earlier, the thread-agility model of ASP.NET made CallContext unstable . stay ASP.NET 4 (MVC 5) And earlier , ASP.NET Of Thread agile model enables CallContext unstable .Thus in ASP.NET the only safe way to achieve the behavior of a per-request logical context, was to use HttpContext.Current.Items. therefore , stay ASP.NET in , The only safe way to implement the logical context behavior of each request is to use HttpContext.Current.Items.Under the covers, HttpContext.Current.Items is implemented with CallContext , but it is done in a way that is safe for ASP.NET. stay CallContext , HttpContext.Current.Items Yes, it is CallContext Realized , But it is in a way ASP.NET In a safe way .
In contrast, in the context of OWIN/Katana Web API, the thread-agility model was not an issue. by comparison , stay OWIN/Katana Web API In the context of , The threading agile model is not a problem .I was able to use CallContext safely, after careful considerations of how correctly to dispose it . stay Consider carefully how to handle CallContext after , I can safely use CallContext.
But now I'm dealing with ASP.NET Core. But now I'm dealing with ASP.NET Core.I would like to use the following middleware: I want to use the following middleware :
public class MultiTenancyMiddleware{ private readonly RequestDelegate next; static int random; private static AsyncLocal<string> tenant = new AsyncLocal<string>(); //This is the new form of "CallContext". public static AsyncLocal<string> Tenant { get { return tenant; } private set { tenant = value; } } //This is the new verion of [ThreadStatic]. public static ThreadLocal<string> LocalTenant; public MultiTenancyMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { //Just some garbage test value... Tenant.Value = context.Request.Path + random++; await next.Invoke(context); //using (LocalTenant = new AsyncLocal<string>()) { // Tenant.Value = context.Request.Path + random++; // await next.Invoke(context); //} }}So far, the above code seems to be working just fine. up to now , The above code Seems to be Well done .But there is at least one red flag. But there is at least one danger sign .In the past, it was critical to ensure that CallContext was treated like a resource that must be freed after each invocation. In the past , Ensure that CallContext Resources that are considered to have to be released after each call are critical .
Now I see there is no self-evident way to "clean up" AsyncLocal . Now I see no self-evident way to “ clear ” AsyncLocal .
I included code, commented out, showing how ThreadLocal<T> works. I included the code , Commented out , It shows ThreadLocal<T> How it works .It is IDisposable , and so it has an obvious clean-up mechanism. It is IDisposable , So it has an obvious cleaning mechanism .In contrast, the AsyncLocal is not IDisposable . by comparison , AsyncLocal No IDisposable .This is unnerving. It's disturbing .
Is this because AsyncLocal is not yet in release-candidate condition? This is because AsyncLocal Is it not in the release candidate status yet ?Or is this because it is truly no longer necessary to perform cleanup? Or is it because you really no longer need to perform cleanup ?
And even if AsyncLocal is being used properly in my above example, are there any kinds of old-school "thread agility" issues in ASP.NET Core that are going to make this middleware unworkable? Even if I used it correctly in my example above AsyncLocal ,ASP.NET Core Is there any kind of old-fashioned “ Line AsyncLocal sex ” The problem will make the middleware unusable ?
Special Note In particular
For those unfamiliar with the issues CallContext has within ASP.NET apps, in this SO post, Jon Skeet references an in-depth discussion about the problem (which in turn references commentary from Scott Hanselman ). For those unfamiliar with ASP.NET In the application CallContext The person with the problem , stay This article SO In the article ,Jon Skeet Refer to the An in-depth discussion of this issue ( Quote in reverse 了 Scott Hanselman The comments ).This "problem" is not a bug - it is just a circumstance that must be carefully accounted for. This “ problem ” It's not a mistake —— It is just a case that must be considered carefully .
Furthermore, I can personally attest to this unfortunate behavior. Besides , I can personally prove this unfortunate behavior .When I build ASP.NET applications, I normally include load-tests as part of my automation test infrastructure. When I build ASP.NET Application time , I usually use load testing as part of an automated test infrastructure .It is during load tests that I can witness CallContext become unstable (where perhaps 2% to 4% of requests show CallContext being corrupted. I have also seen cases where a Web API GET has stable CallContext behavior, but the POST operations are all unstable. The only way to achieve total stability is to rely on HttpContext.Current.Items. During the load test , I can see CallContext Become unstable ( There may be 2% To 4% The request for shows CallContext Damaged . I also see Web API GET With stable CallContext Behavior , but POST Unstable operation . The only way to achieve complete stability is to rely on HttpContext.Current.Items.
However, in the case of ASP.NET Core, I cannot rely on HttpContext.Items...there is no such static access point. however , stay ASP.NET Core Under the circumstances , I can't rely on HttpContext.Items... There is no such static access point .I'm also not yet able to create load tests for the .NET Core apps I'm tinkering with, which is partly why I've not answered this question for myself. I'm not ready for what I'm mending .NET Core Application create load test , This is part of the reason why I didn't answer this question for myself .:):)
Again: Please understand that the "instability" and "problem" I'm discussing is not a bug at all. Again : Please understand what I am discussing “ unstable ” and “ problem ” It's not a mistake at all .CallContext is not somehow flawed.CallContext There is no defect .The issue is simply a consequence of the thread dispatch model employed by ASP.NET. The problem is just ASP.NET The results of the adopted thread scheduling model .The solution is simply to know the issue exists, and to code accordingly (eg use
HttpContext.Current.Itemsinstead ofCallContext, when inside an ASP.NET app). The solution is simply to know that the problem exists , And code accordingly ( for example , stay ASP.NET Internal to the application , UseHttpContext.Current.Itemsinstead ofCallContext).
My goal with this question is to understand how this dynamic applies (or does not) in ASP.NET Core, so that I don't accidentally build unstable code when using the new AsyncLocal construct. My goal with this question is to understand how this dynamic works in ASP.NET Core Application in ( Or not applied ), In order to use the new AsyncLocal Construction does not accidentally build unstable code .
Solution :
Reference resources : https://stackoom.com/en/question/2TCF1边栏推荐
- Cs8126t 3.1w mono ultra low EMI unfiltered class D audio power amplifier IC
- Viewing Chinese science and technology from the Winter Olympics (V): the Internet of things
- [Suanli network] problems and challenges faced by the development of Suanli network
- JS dynamic table creation
- Kotlin reflection -- Notes
- [short time average zero crossing rate] short time average zero crossing rate of speech signal based on MATLAB [including Matlab source code 1721]
- Analysis of common interview questions in redis
- Arm instructions and others
- How two hosts in different network segments directly connected communicate
- How do I check swift if two arrays contain the same elements, regardless of the order in which they appear?
猜你喜欢

Cs8683 (120W mono class D power amplifier IC)

At the age of 26, I was transferred to software testing with zero foundation. Now I have successfully entered the job with a monthly salary of 12K. However, no one understands my bitterness

Methods for obtaining some information of equipment
![[data visualization application] draw spatial map (with R language code)](/img/2d/04e5015573d10bdd6325ae497bfeb3.jpg)
[data visualization application] draw spatial map (with R language code)
![[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management](/img/62/dab2ac0526795f2040394acd9efdd3.jpg)
[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management

Monitoring access: how to grant minimum WMI access to the monitoring service account

Sleep quality today 67 points

sin(a+b)=sina*cosb+sinb*cosa的推导过程

3-7sql injection website instance step 3: attack type and attack strategy

Cs8126t 3.1w mono ultra low EMI unfiltered class D audio power amplifier IC
随机推荐
[no title] dream notes 2022-02-20
A + B Again
What is the IP address
Analysis report on demand scale and Supply Prospect of global and Chinese thermal insulation materials market during the 14th Five Year Plan period 2022-2028
After unplugging the network cable, does the original TCP connection still exist?
JSON. toJSONString(object, SerializerFeature.WriteMapNullValue); Second parameter action
China rehabilitation hospital industry operation benefit analysis and operation situation investigation report 2022
Can TCP syn handshake messages transmit data
The five minute demonstration "teaches" actors to speak foreign languages and can seamlessly switch languages. This AI dubbing company has just received a round a financing of 20million US dollars
百度地图——入门教程
[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management
@Detailed explanation of valid annotation usage
[core content and derivation] the mystery of human memory system may be just like this
Highway
Query process of MySQL secondary index
ctfshow-misc
Drosophila played VR and entered nature. It was found that there were attention mechanisms and working memory. The insect brain was no worse than that of mammals
Forecast report on output demand and supply scale of global and Chinese structural ceramics market for semiconductor equipment (2022 Edition)
With a younger brother OCR, say no to various types of verification codes!
Ht81293 built in adaptive dynamic boost 20W mono class D power amplifier IC solution