InvalidOperationException异常:因为不同的线程拥有它调用线程不能访问该对象。 [英] InvalidOperationException: The calling thread cannot access this object because a different thread owns it.

查看:1058
本文介绍了InvalidOperationException异常:因为不同的线程拥有它调用线程不能访问该对象。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
调用线程不能因为不同的线程拥有它

错误:

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



代码:

Code:

public partial class MainWindow : Window
    {
        Thread t;
        bool interrupt;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btss_Click(object sender, RoutedEventArgs e)
        {
            if (t == null)
            {
                t = new Thread(this.calculate);
                t.Start();
                btss.Content = "Stop";
            }
            else
            {
                t.Interrupt();
            }

        }

        private void calculate()
        {
            int currval = 2;
            int devide = 2;
            while (!interrupt)
            {
                for (int i = 2; i < currval/2; i++)
                {
                    if (2 % i != 0)
                    {
                        lbPrimes.Items.Add(currval.ToString()); //Error occures here
                    }
                }
                currval++;
            }
        }
    }



什么会导致此,我怎样才能解决这个问题?

What would be causing this, and how can I resolve it?

推荐答案

您需要重新加入主UI线程,以影响UI。您可以检查这是否需要使用 InvokeRequired ,并引用控件之前实现调用。

You need to rejoin the main UI thread in order to affect the UI. You can check whether this is needed with InvokeRequired, and implement Invoke before referencing the controls.

private void calculate()
{
    if (InvokeRequired)
    {
        Invoke(new Action(() => calculate()));
    }
    else
    {
      //
    }
 }

这篇关于InvalidOperationException异常:因为不同的线程拥有它调用线程不能访问该对象。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆