由于运行项目而发生错误 [英] error occuring due to run projct

查看:85
本文介绍了由于运行项目而发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hei,
我在做项目时遇到一个错误

Hei,
i am doing project in that i got one error

Cross-thread operation not valid: Control 'lblEmergencyStopIndicator' accessed from a thread other than the thread it was created on.

推荐答案

您只能从在以下位置创建的线程访问用户界面(或UI)组件:UI线程.如果尝试从其他线程访问它们,则会收到此错误.

解决方案是改为调用控件.
举个例子,假设您想从后台线程向Tabpage添加新的Tab.您要做的就是检查并在必要时调用:

You can only access User Interface (or UI) components from the thread they were created on: the UI thread. If you try to access them from a different thread, you will get this error.

The solution is to Invoke the control instead.
Fore exampole, suppose you want to add a new Tab to a Tabpage from a background thread. All you have to do is check, and invoke as necessary:

private void AddNewTab(string tabName)
    {
    if (InvokeRequired)
        {
        Invoke(new MethodInvoker(delegate { AddNewTab(tabName); }));
        }
    else
        {
        TabPage tp = new TabPage(tabName);
        myTabControl.TabPages.Add(tp);
        }
    }


您无法从非UI线程调用与UI相关的任何操作.相反,您需要使用System.Windows.Threading.DispatcherInvokeBeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms).

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview扫描仪和MD5的问题 [如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

—SA
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


这篇关于由于运行项目而发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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