C# Windows 窗体中的线程错误 [英] Thread error in C# Windows Form

查看:36
本文介绍了C# Windows 窗体中的线程错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误:

System.InvalidOperationException"类型的未处理异常发生在 System.Windows.Forms.dll

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

附加信息:跨线程操作无效:控制从创建它的线程以外的线程访问Redlight"

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

Redlight 和 Greenlight 是图片框.基本上,我希望它能够做的就是每秒在每张图片之间交替.我在这个网站上搜索过类似的错误,我看到它与调用"有关,但我什至不知道那是什么,有人能指教我吗?

Redlight and Greenlight are pictureBoxes. Basically, all I want it to be able to do is alternate between each picture every second. I searched on this website for similar errors, I see it has to do with "Invoking", but I don't even know what that is, can someone enlighten me?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace EMCTool
{
    public partial class EMCTool_MainForm : Form
    {
        bool offOn = false;

        public EMCTool_MainForm()
        {
            InitializeComponent();
        }

        private void EMCTool_MainForm_Load(object sender, EventArgs e)
        {
            System.Threading.Timer timer = new System.Threading.Timer(new System.Threading.TimerCallback(timerCallback), null, 0, 1000);
        }

        private void timerCallback(object obj)
        {
            if (offOn == false)
            {
                Redlight.Show();
                offOn = true;
            }
            else
            {
                Greenlight.Show();
                offOn = false;
            }
        }
    }
}

推荐答案

当您尝试从不是在其上创建的任何线程更新 UI 元素时,您会收到跨线程错误.

You get the Cross-thread error when you try to update a UI element from any thread it was not created on.

Windows 窗体中的控件绑定到特定线程并且不是线程安全的.因此,如果您从不同的线程调用控件的方法,则必须使用控件的调用方法之一将调用编组到正确的线程.此属性可用于确定是否必须调用 invoke 方法,如果您不知道哪个线程拥有控件,这会很有用.

Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.

请参阅此处了解更多信息

试试这个.这对我来说很好

Try this .This works fine for me

   if (pictureBoxname.InvokeRequired)
                    pictureBoxname.Invoke(new MethodInvoker(delegate
                    {
          //access picturebox here
                    }));
                else
        {

  //access picturebox here
}   

这篇关于C# Windows 窗体中的线程错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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