Willis.Hu
Willis.Hu

Reputation: 265

Set the CurrentPrincipal failed when using UI event In Winform

All

I met an issue when I trying to set Thread.CurrentPrincipal on a WinForm Application.

There are two button on Form, Button1 and Button2. Button1 set the Thread.CurrentPrincipal and Button2 show the CurrentPrincipal. Everything works well so far.

private void button1_Click(object sender, EventArgs e)
{
        SetPermission();
}

private void SetPermission()
{
        Thread.CurrentPrincipal = new MyPrinciple() { User = "xxxx" };
}

private void button2_Click(object sender, EventArgs e)
{
        Console.WriteLine("Tread principal:{0},{1}", Thread.CurrentThread.Name, Thread.CurrentPrincipal.ToString());
}

Then I changed some code. I want to auto set the principal once Form shown.So I added a event on Form.Shown.

void Form1_Shown(object sender, EventArgs e)
{
        Dispatcher.CurrentDispatcher.Invoke(new Action(() => { SetPermission(); }));
}

public Form1()
{
        InitializeComponent();
        this.Shown += Form1_Shown;
}

When I click the button2 to show the princpal, I saw nothing.

I tried to set the principal on the Form's constructor. Then I got the result expected when I clicked button2.

public Form1()
{
        InitializeComponent();
        //this.Shown += Form1_Shown;
        SetPermission();
}

I searched on Google, By now, I have no idea about it. What's the different between those two ways?

Thanks you very much.

Upvotes: 1

Views: 77

Answers (1)

Wolfgang
Wolfgang

Reputation: 896

try to use

AppDomain.CurrentDomain.SetThreadPrincipal(new MyPrinciple() { User = "xxxx" })

instead of

Thread.CurrentPrincipal = new MyPrinciple() { User = "xxxx" };

Upvotes: 1

Related Questions