如何解决“跨线程操作无效” [英] How to solve "cross-thread operation not valid"

查看:89
本文介绍了如何解决“跨线程操作无效”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 我有一个需要在线程上运行的void。基本上程序首先得到`checkboxlist.Items.Count`然后在迭代完成时从中减去1。但是当它在第一次添加值时,它会抛出"跨线程操作无效",从一个线程中获取
,而不是创建它的线程。我读到这是因为
不安全线程(?)并且有解决方案但是 我无法了解如何将它们应用到我的码。
所以一个例子的答案真的很好。



   

 for(int i = 0; i< cbox.Items.Count; i ++)
{
if(cbox.GetItemChecked(i) )== true)
{
itr ++;
}
}

for(int i = 0; i< cbox.Items.Count; i ++)
{
if(cbox.GetItemChecked (i)== true)
{
left.Text =(itr.ToString()+" /" + cbox.Items.Count)
// CODE //
itr--;
}
}


谢谢..




解决方案

我认为这是因为组合框由UI线程创建,只有UI线程可以更改它。因此,如果您尝试访问combox组合框抛出,则有另一个不是它们的创建者的线程。您需要切换上下文bach到UI线程。


您可以尝试使用InvokeRequired
https://msdn.microsoft.com/cs-cz/library/system.windows.forms.control.invokerequired(v = vs.110).aspx


 I have a void that needs to run on a thread. Basically program first gets `checkboxlist.Items.Count` then subtracts 1 from it when an iteration completes. But when it adds the value at the first for it throws `Cross-thread operation not valid 'left accessed from a thread than the thread it was created on`. I read that this is because of not safe threading(?) and there was solutions but I couldn't get how to implement them to my code. So an answer with an example would be really good.

   

for (int i = 0; i < cbox.Items.Count; i++)
{
    if (cbox.GetItemChecked(i) == true)
    {
        itr++;
    }
}

for (int i = 0; i < cbox.Items.Count; i++)
{
    if (cbox.GetItemChecked(i) == true)
    {
        left.Text = (itr.ToString() + "/" + cbox.Items.Count)
        //CODE//
        itr--;
     }
}

Thanks..


解决方案

I think it is because combobox is created by UI thread and only UI thread can change it. So if you try to access into combox combobox throws there is another thread which is not creator of them. You need switch context bach to UI thread.

You can try use InvokeRequired https://msdn.microsoft.com/cs-cz/library/system.windows.forms.control.invokerequired(v=vs.110).aspx


这篇关于如何解决“跨线程操作无效”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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