ThreadPool class, there are two methods we do not use,unsafequeueuserworkitem and unsaferegisterwaitforsingleobject. in order to fully understand these methods, first of all, we must recall. NET Framework of how security policy works.
Windows security is about resources. The operating system itself allows permissions to be set on files, users, registry keys, and any other system resources. This approach is very effective for user authentication of the application system, but it has some limitations when there is a situation where the user has no confidence in the system he is using. For example, these programs are downloaded from the Internet. In this case, once the user installs the program, it can perform any action within the scope of the user's permission. For example, if a user can delete any shared files in his company, any program downloaded from the Internet can do the same.
. NET provides the security policy applied to the program, not the user. This means that, within the scope of user rights, we can limit the resources that are used by any execution unit (assembly). With MMC, we can define a set of assemblies based on conditions and then set different policies for each group, a typical example of which is restricting access to the disk from programs downloaded from the Internet.
In order for this function to work, the. NET framework must maintain a call stack between different assemblies. Suppose an app does not have permission to access the disk, but it calls a class library that is accessible to the entire system, and when the second Assembly performs a disk operation, the permissions set to that assembly allow this, but permissions are not applied to the calling assembly. NET not only checks the permissions of the current assembly, but also checks the entire call stack for permissions. This stack has been highly optimized, but they add an additional burden to calls between two different assemblies.
Unsafequeueuserworkitem , unsaferegisterwaitforsingleobject and QueueUserWorkItem , RegisterWaitForSingleObject two methods are similar. Because non-secure versions do not maintain their call stacks between functions, the unsecured version runs faster. However, the callback function will only execute under the security policy of the current Assembly, and it will not be able to apply permissions to the assembly in the entire call stack.
My advice is to use a non-secure version only in extreme situations where performance is very important and security is already under control. For example, if you build an application that is not called by another assembly, or is used only by a well-defined assembly, you can use a non-secure version. If you are developing a class library that will be used by third-party applications, you should not use these methods because they may use your library to gain access to system resources.
[. NET multithreading] Security mechanisms for ThreadPool