0

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?

1
  • you can't access the checkbox control in a thread outside of the form. You created a new thread and are using the checkbox in that new thread. You can't do that Commented Mar 19, 2013 at 16:39

4 Answers 4

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to mark a post as an answer if it solves your problem.
0

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

1 Comment

checkBox1.InvokeRequired, this is for Winform, not WPF
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.