0

大家好,我收到一个例外if (checkBox1.IsChecked == true || checkBox2.IsChecked == true)

调用线程无法访问此对象,因为不同的线程拥有它。

在我的 wpf 应用程序中:

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();
       }
    }
}

为什么?

4

4 回答 4

3

您不能从创建的线程以外的线程访问 UI 元素。您的复选框是在 UI 线程上创建的,您只能在 UI 线程上访问这些复选框。尝试这个。

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);
}
于 2013-03-19T16:42:16.133 回答
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.

于 2013-03-19T16:44:47.273 回答
0

您不能在与 UI 不同的线程上访问 UI 元素。要解决此问题,您可以检查

checkBox1.Dispatcher.CheckAccess()

如果为真,请使用

checkBox1.Dispatcher.Invoke

或者

checkBox1.Dispatcher.BeginInvoke
于 2013-03-19T16:41:28.693 回答
0

使用CheckAccess查看是否需要调用Dispatcher.BeginInvoke或 Invoke 另请参阅此帖子

于 2013-03-19T16:41:31.867 回答