wpf应用程序中的线程异常

时间:2013-03-19 16:36:40

标签: c# wpf

大家好我收到例外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 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

checkBox1.Dispatcher.CheckAccess()

如果为true,请使用

checkBox1.Dispatcher.Invoke

checkBox1.Dispatcher.BeginInvoke

答案 2 :(得分:0)

使用CheckAccess查看是否需要致电Dispatcher.BeginInvoke或调用 另请参阅this post

答案 3 :(得分:0)

基本上,不允许您从创建它们的线程以外的线程访问控件。 WPF线程模型here有一个很好的解释,this遍历你所描述的问题。

祝你好运。