螺纹设置标识螺纹、标识

2023-09-02 02:04:02 作者:哼!

在C#中,如何设置一个主题的身份?

In C#, how do I set the Identity of a Thread?

例如,如果我有线程MyThread,它已经启动,可以更改MyThread的身份?

For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?

或者,这是不可能的?

推荐答案

您可以通过创建一个新的主要设置线程的身份。您可以使用继承关System.Principal.IIdentity任何身份,但你需要一个继承关System.Principal.IPrincipal这需要认同你所使用的类型。为了简单起见.NET框架提供的GenericPrincipal和GenericIdentity可以使用这样的:

You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits off System.Principal.IIdentity, but you need a class that inherits off System.Principal.IPrincipal that takes the type of Identity you are using. For simplicity sake the .Net framework provides GenericPrincipal and GenericIdentity which can be used like this:

        using System.Security.Principal;

        // ...

        GenericIdentity identity = new GenericIdentity("M.Brown");
        identity.IsAuthenticated = true;

        // ...

        System.Threading.Thread.CurrentPrincipal =
            new GenericPrincipal(
                identity,
                new string[] { "Role1", "Roll2" }
                );

        //...

        if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Roll1"))
        {
            Console.WriteLine("Permission denied");
            return;
        }

使用新的身份这不但是给你的窗口权利的东西。但它可以,如果你正在开发一个网站,并希望创建自己的用户管理是有益的。

This won't however give you windows rights to stuff using the new identity. But it can be useful if you are developing a web site and want to create your own user management.

如果你想pretend是一个不同的Windows用户比目前正在使用,那么你需要使用模拟账户。如何做到这一点的一个例子可以在帮助中找到的 System.Security.Principal .WindowsIdentity.Impersonate()。有一些限制有关,占你下运行可以模拟该帐户。

If you want to pretend to be a different Windows user than the account you are currently using then you need to use impersonation. An example of how to do this can be found in the Help for System.Security.Principal.WindowsIdentity.Impersonate(). There are limitations about which accounts the account you are running under can impersonate.

在某些情况下,.NET Framework并不是模仿你。在哪里发生这种情况的一个例子是,如果你正在开发一个ASP.Net网站,并有集成Windows身份验证接通您在运行的虚拟目录或网站。

In some cases the .Net framework does impersonation for you. One example of where this occurs is if you are developing a ASP.Net web site and you have Integrated Windows Authentication switched on for the virtual directory or site you are running in.

 
精彩推荐
图片推荐