在另一个线程中访问表单窗口 [英] Accessing Form Window in another thread

查看:82
本文介绍了在另一个线程中访问表单窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在另一个线程的窗口的列表框中添加条目. 我的问题是,我必须穿线. 一个工作线程,它完成所有实际工作,一个线程用于我要显示状态信息的窗口. 我试图将窗体窗口作为构造函数中的参数传递,但是当我调用它时,我遇到了异常.

How do i add an entry in a listbox in a window that is in another thread. My Problem is, that i have to threads. One working thread, that does all the actual work and one thread for a window where i want to display status information. I tried to pass the form window as paramater in the constructor, but when i call it i get an exception.

以下是我的一些代码来说明问题:

Here is some of my code to illustrate the problem:

public partial class Mainform : Form
{
    private string db = String.Empty;
    private string password = String.Empty;
    private string sqlinifile = String.Empty;
    DatabaseListener dbListener;
    StatusWindow statusWindow;

    public Mainform()
    {
        //
        // The InitializeComponent() call is required for Windows Forms designer support.
        //
        InitializeComponent();

        //
        // TODO: Add constructor code after the InitializeComponent() call.
        //
        db = "EWAG";
        password = "secret";
        sqlinifile = "C:\\Programme\\Unify\\Team Developer 5.2\\sql.ini";
        textBoxDB.Text = db;
        textBoxPwd.Text = password;
        textBoxSqlIni.Text = sqlinifile;

        statusWindow = new StatusWindow();
        dbListener = new DatabaseListener(statusWindow);
    }

    public void threadStarter()
    {
        this.dbListener.startSynchronizing(5);

    }
    void Button1Click(object sender, EventArgs e)
    {
        this.db = textBoxDB.Text;
        this.password = textBoxPwd.Text;
        this.sqlinifile = textBoxSqlIni.Text;

        if (dbListener.connectToDatabase(db,"sysadm", password, sqlinifile)) 
        {
            this.Hide();
            statusWindow.Show();
            Thread synchronizer = new Thread(new ThreadStart(threadStarter));
            synchronizer.Start();

        }
    }       

}

推荐答案

使用.Invoke(),卢克.

认真地,要从另一个线程与表单上的某些控件进行对话,您必须Invoke()一些方法,以便与窗口句柄对话的属性设置器被序列化到主UI线程及其消息泵.

Seriously, to talk to some controls on the form from another thread, you have to Invoke() some method so the property setters that talks to window handles are serialized to main UI thread and it's message pump.

或者,使用主UI线程上的计时器来收集信息并将其放在列表框中.

Alternatively, use timer that is on the main UI thread to gather information and put them in the listbox.

或者使用混合方法,一个线程收集数据,将其放入未绑定到UI的队列中,并使用计时器将其出队并在表单上显示数据.我之所以使用它,是因为接收数据速率太大,并且会阻塞UI.

Or use hybrid approach, one thread to gather the data, put it into queue that is not tied into UI, and timer to dequeue it and display data on the form. I used it on occasion because receiving data rate was too big and it would block the UI.

这篇关于在另一个线程中访问表单窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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