saf
saf

Reputation: 3

Exce­pti­on with th­re­ads in ­wp­f a­pp

Hi guys I receive an exception if (checkBox1.IsChecked == true || checkBox2.IsChecked == true):

The calling thread cannot access this object because a different thread owns it.

in my wpf app:

private void button1_Click(object sender, RoutedEventArgs e)
{
    int i = 0;
    int j = Int32.Parse(textBox1.Text);
    thr = new Thread[j];
    for (; i < j; i++)
    {
        thr[i] = new Thread(new ThreadStart(go));
        thr[i].IsBackground = true;
        thr[i].Start();
    }
}

public void go()
{
    while (true)
    {
       string acc = "";
       string proxy = "";
       if (checkBox1.IsChecked == true || checkBox2.IsChecked == true)
       {
           if (checkBox1.IsChecked == true)
               Proxy.type = "http";
           else if (checkBox2.IsChecked == true)
               Proxy.type = "socks5";
           else
               Proxy.type = "none";
           proxy = rand_proxy();
       }
    }
}

Why?

Upvotes: 0

Views: 95

Answers (4)

dotcomslashnet
dotcomslashnet

Reputation: 148

Basically you're not allowed to access controls from threads other than the thread they were created on. There's a good explanation of the WPF threading model here, and this walks through the issue you are describing.

Good luck.

Upvotes: 0

user786981
user786981

Reputation:

You cannot access UI elements from a thread other than one which was those created. Your check boxes are created on UI thread and you can access these only on UI thread. try this.

public void go()
    {
        Dispatcher.BeginInvoke(new Action(()=>{
        while (true)
        {
            string acc = "";
            string proxy = "";
            if (checkBox1.IsChecked == true || checkBox2.IsChecked == true)
            {
                if (checkBox1.IsChecked == true)
                    Proxy.type = "http";
                else if (checkBox2.IsChecked == true)
                    Proxy.type = "socks5";
                else
                    Proxy.type = "none";
                proxy = rand_proxy();
            }
}), null);
}

Upvotes: 3

David
David

Reputation: 16277

Use CheckAccess to see if you need call Dispatcher.BeginInvoke or Invoke See also this post

Upvotes: 0

Justin Pihony
Justin Pihony

Reputation: 67075

You cannot access UI elements on a different thread than the UI. To work around this, you can check

checkBox1.Dispatcher.CheckAccess()

and if true, use

checkBox1.Dispatcher.Invoke

or

checkBox1.Dispatcher.BeginInvoke

Upvotes: 0

Related Questions