ASP.Net SafeHandle - tasks and examples - asp.net

I want to understand how to work with unmanaged resources and when I need the SafeHandle class. What can be the problem statement when you can say: "Oh, here I need the SafeHandle class!"?
I would be grateful for links to articles, examples, explanations

I think MSDN is pretty clear in definition:
The SafeHandle class provides critical finalization of handle
resources, preventing handles from being reclaimed prematurely by
garbage collection and from being recycled by Windows to reference
unintended unmanaged objects. Before the .NET Framework version 2.0,
all operating system handles could only be encapsulated in the IntPtr
managed wrapper object.
The SafeHandle class contains a finalizer that ensures that the handle
is closed and is guaranteed to run, even during unexpected AppDomain
unloads when a host may not trust the consistency of the state of the
AppDomain.
For more information about the benefits of using a SafeHandle, see
Safe Handles and Critical Finalization.
This class is abstract because you cannot create a generic handle. To
implement SafeHandle, you must create a derived class. To create
SafeHandle derived classes, you must know how to create and free an
operating system handle. This process is different for different
handle types because some use CloseHandle, while others use more
specific methods such as UnmapViewOfFile or FindClose. For this
reason, you must create a derived class of SafeHandle for each
operating system handle type; such as MySafeRegistryHandle,
MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived
classes are prewritten and provided for you in the
Microsoft.Win32.SafeHandles namespace.

Related

ASP.NET DbContext instance injection but not used - performance issue or not?

Latest approach says about injecting DbContext instance right to the MVC\WebAPI controller. It has a number of pros but I have one question which is not answered yet - performance of the DbContext instance creation which will not be used.
According to this question: What happens when i instantiate a class derived from EF DbContext? DbContext creation is not so cheap operation (both memory and CPU). And it's twice bad when:
Your action doesn't need the DbContext at all (so you have a mix actions which use and not use the DB)
Some logic (e.g. conditions) doesn't allow to access the DbContext (e.q. ModelState.IsValid). So action will return result BEFORE access to the DbContext instance.
So in both (an maybe some other cases) DI creates a scoped instance of the DbContext, wastes resources on it and then just collect it at the end of the request.
I didn't make any performance tests, just googled for some articles firsts. I don't say that it will be 100% lack of the performance. I just thought: "hey man, why have you created the instance of the object if I will not use it at all".
Why have you created the instance of the object if I will not use it
at all.
Mark Seemann said in his book Dependency Injection in .NET, "creating an object instance is something the .Net Framework does extremely fast. any performance bottleneck your application may have will appear in other place, so don't worry about it."
Please note that Dbcontext enables lazy loading by default. Just by instantiating it, it doesn't have much impact on the performance. So, I would not worry about Dbcontext.
However, if you have some custom classes doing heavy lifting inside constructor, then you might want to consider refactoring those.
If you really want to compare the performance, you could wrap those dependencies with Lazy, and see how much performance you gain. Does .net core dependency injection support Lazy.
You could register it as Lazy or you could do what I do and just inject IMyDbContextFactory and then you can call Create() that will return the DbContext when you actually need it (with its own pros/cons). If the constructor doesn't do anything, it won't be a huge hit, but keep in mind that the first time it gets newed up, it will hit the static constructor that goes through and does all the model validation. This hit only happens once, but it is a huge hit.

Objects creation lifetime in Asp.net MVC5

Controllers are created per request in Asp.net MVC, this is a fact.
My question is:
what is the best practice for for creating common objects (Logger, Localizer, Configurator) that are used in the web application, possible methods from my knowledge are:
Create the object per request then dispose it at the end of the request.
Create the object at the beginning of user session then dispose it at the end of the session.
Create only one object for the entire application and dispose it at application shutdown.
It depends entirely on the scope within these components are used and their dependencies, to elaborate:
Logger
A logger is usually alive throughout the entire lifespan of the application and can be used all over the application (scope), the logger doesn't care for the request or the controller (dependencies). Best Lifetime Scope: Application.
LogSource / LogContext
Unlike logger, LogSource / LogContext are contextual object that are to be used withing a given context (scope), these object are aware of their context (controller / request) (dependencies). Best Lifetime Scope: Controller / Request.
Localizer
Localizer is a bit less clear-cut as the other components. For one it is use application wide (Controllers, Views etc.) (scope). But as for its dependencies the matter is implementation specific, your localizer may need a CultureInfo object for construction or it may not. In a case when it is not required then there are no dependencies for that component and an Application scope will fit.
On the other hand if a culture is required then it is a dependency for that component. Now it's logical to then scope it to a user session but this is where the idea of performance and dependency specifics comes to play. If you scope the localizer to a user session then each user will have x amount of time the server to read the localization file before it's served its response. Additionally the dependency is not the user session but the user's culture, whilst the possible user sessions are infinite, the possible supported locals are all but infinite. Keeping that in mind you can then create a localization pool that contains every supported local (and possibly a fallback local for the ones that aren't supported),scoped to the application, which can serve localizers scoped to user sessions.
To sum up - You can apply the scope-dependencies logic to any component but as we've seed with the localizer it's always best to understand the component and the implication of scoping that component to a specific scope.
It really depends on 2 things:
The implementation of those common objects - for example thread safety. For example if your logger has a singleton life-cycle and it has some static property (for example level or a name) then by modifying it in one request it will affect others (and this most probably is unwanted behavior).
The purpose(usage) of those objects - lets assume that you have a LoggerManager or a Configurator or some kind of Factory object that should be initialized only once on application start and then it is used to create(retrieve) other objects (for example an IoC container)then it is certainly makes sense to make it singleton (sometimes it is absolutely required).
From my experience most of the objects have either transient or per-request life cycle. Regarding the singletons (one object for the entire application) - usually it is very clear when to use them. I think a god example is a LoggerManager that is used to create Logger instances based on some static configuration or a Configurator (as you called it) that is initialized on application start and parses some configuration files. My rules of thumb for singletons are:
they have to be thread-safe
they don't change often
they either hold some shared data that is applicable to all threads/requests/users and etc
they are heavy objects - if they are light weight you can create a new object each time (transient life-cycle) and most probably you won't notice any difference in performance.
Regarding the session - for me it is more of a cache, so most of the time it holds some user related data

How to introduce application-wide context object?

I need to make several properties accessible from application's business layer. Those are some ids and common settings. Most of them are valid only through request-response lifespan.
This is a web application (ASP.NET Web Forms to be specific) with dependency injection set up.
Currently those properties are passed through method parameters directly to business layer's services. That works but is not very efficient since:
sometimes parameters' values need to be passed deeper obscuring the readability a bit
some properties should be lazy resolved, and this should be done only once per request
retrieving properties which are resolved by touching a database can be confusing for new developers (there is not unified way of doing this)
some services are constructed by a factory which enriches them with some config parameters
I was thinking about introducing an application context interface, with an implementation in the main project, which would be created on every request. It could be injected to the services directly making them parametrized automatically and independently (services won't need the factory anymore).
Is it how this problem should be tackled or maybe there are some other options?
One option I don't like here is that it might bond the main particle with business layer which is not a perfect example of The Clean Architecture.
Id say you solution is a very common one - inject an 'application context' into your classes. One thing I would be careful of though is making sure you are following the Integration Segregation Principle (from SOLID). Dont just start making all your classes expect an application context instance. Instead, design interfaces that split the application context up, and have your classes expect them as dependencies. Your application context will then need to implement all the interfaces.
This is the correct way to do things as it decouples your classes from implementation. Really your classes don't care if their dependency is from one giant application context, they just care about specific methods implemented by it. This will make your code more robust as you will reduce the risk of breaking something if you change the implementation of the application context later on.
Why don't you use some dependency injection container? Your global settings and parameters can be registered to it as pseudo-singletons and then you will be able to neatly request them from any point inside your application.

Should instance variables not be used since they cause mulithreading problems?

I understand that instance variables are not thread safe because they are stored on the heap. I am refactoring code in an ASP.NET single threaded application and I am trying to use instance variables more.
My question is: do developers avoid using instance variables because of possible multi threading problems? (even if the app is not multi threaded now it may be in the future). I remember reading that instance variables should be used to improve design using composition and aggregation rather than association (as with local variables).
Is there any criteria that helps a developer to decide when to use instance variables and when to use local variables. I have Googled this and I have looked on MSDN but I have not managed to find an answer to my specific question.
Have you done anything to make the ASP.NET application single threaded? Otherwise it's multi treaded by default.
Instance variables is only a problem with multi threaded applications if you share the object between threads. Normal for an ASP.NET application is that each thread creates its own instances of the objects, so the multi threading is not a problem.
If you need to share data between threads, encapsulating the data in an object is still the best approach. By using private instance variables and access them through methods or properties, you can make sure that all access from outside the object is synchronised, as the code in the object has full control over where the data is exposed.
You are in fact referring to static variables. Static variables are not thread-safe (in general, unless you write code to synchronize appropriate access to the variable). Instance variables, in contrast, are thread-safe in asp.net since each request thread will operate on its own copy.
static variables are meant to store data that needs to be shared among all requests. If you don't have such scenario, you shouldn't need to use static variables. And if you do, there are classes that already provide for this, such as the Cache class.
Assuming are talking about web pages and instance variable of web page then you do not have to worry about the multi-threading and thread safety. The asp.net/web server will take care for that. This msdn article discuss the thread safety provide by asp.net.

Thinking with Threads in asp.net

I've got a static class that has a private dictionary object. This object is initialized in the static constructor, and is then modified every time a TimerElapsed event is raised by a timer object (also located in the static class).
My pages use a get() method to access the dictionary. These are pages viewable by the public, so many of these may happen at once.
Do I need to worry about locking the dictionary object to prevent a page from trying to read it while it's being updated?
You may find that using ConcurrentDictionary (if you are using .NET 4) to be a more reliable solution. Otherwise you may run in to problems when two or more threads attempt to write (or read/write) at the same time.
If you don't have .NET 4, you may prefer to wrap up your dictionary into a class that uses locks to prevent access to the shared bits so you don't have locks scattered everywhere.

Resources