跨线程操作无效:控件"listBox1"是从创建该线程的线程之外的其他线程访问的. [英] Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on.

查看:74
本文介绍了跨线程操作无效:控件"listBox1"是从创建该线程的线程之外的其他线程访问的.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

plz在此消息中为我提供帮助
跨线程操作无效:从创建该线程的线程之外的线程访问"listBox1"控件.
这是我的代码

plz help me in this message
Cross-thread operation not valid: Control ''listBox1'' accessed from a thread other than the thread it was created on.
this my code

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



namespace Thread
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
               
        
        }
        public void FillLIstBox()
        {
            

            for (int i = 0; ; i++)
            {
                listBox1.Items.Add(i);
            }
        }
        private void BtFill_Click(object sender, EventArgs e)
        {
            System.Threading.Thread thr = new System.Threading.Thread(new System.Threading.ThreadStart(FillLIstBox));
            thr.Start();      
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
    }

推荐答案

您必须与UI线程上的控件进行交互.
您可以使用 Control.InvokeRequired [ Control.Invoke [ ^ ]或Control.BeginInvoke [
You must interact with a control on the UI thread.
You can use Control.InvokeRequired[^] to determine if you''re on the UI tread or not. If you''re not on the UI thread you have to use Control.Invoke[^] or Control.BeginInvoke[^]

In the case you posted using Invoke wouldn''t make sense, but I guess this is not your real case, so you''ll want to do something like the following
int j = i;
listBox1.Invoke(() => listBox1.Items.Add(j));


这篇关于跨线程操作无效:控件"listBox1"是从创建该线程的线程之外的其他线程访问的.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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