Winforms线程问题,第二个线程无法访问第一个主窗体控件 [英] Winforms threading problem, second thread can't access 1st main forms controls

查看:103
本文介绍了Winforms线程问题,第二个线程无法访问第一个主窗体控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个winforms应用程序,问题与线程有关. 由于我正在调用'MyCustomCode(),因此会创建一个新线程并调用该方法 'SomeMethod()'然后访问MessageBox.Show(...).

I have a winforms application, the issue has to do with threading. Since I am calling 'MyCustomCode() which creates a new thread, and calls the method 'SomeMethod()' which then accesses MessageBox.Show(...).

问题与线程有关,因为新创建的线程正在尝试访问 在另一个线程上创建的控件.

The problem has to do with threading, since the newly created thread is trying to access a control that was created on another thread.

我遇到了错误:

跨线程操作无效:控制'TestForm'是从创建该线程的线程之外的线程访问的.

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

public TestForm()
{
    InitializeComponent();


    // custom code
    //
    MyCustomCode();


}

public void SomeMethod()
{

    // ***** This causes an error  ****

    MessageBox.Show(this,   
        ex.Message, 
        "Error", 
        MessageBoxButtons.OK, 
        MessageBoxIcon.Error
    );
}



private void InitializeAutoUpdater()
{
        // Seperate thread is spun to keep polling for updates
        ThreadStart ts = new ThreadStart(SomeMethod);
        pollThread = new Thread(ts);
        pollThread.Start();
}

更新

如果您查看此示例,请 http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx ,方法CheckAndUpdate正在调用MessageBox.Show(..),这就是我的问题所在.我本以为代码很好用!

If you look at this example http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go!

有趣的是该代码在星期五工作得很好?

Funny thing is that this code was working just fine on Friday???

推荐答案

您无法访问来自多个线程的UI元素.

You cannot acces UI elements from multiple threads.

解决此问题的一种方法是调用控件的Invoke方法,并使用UI元素(例如消息框)来委托给该函数.像这样的东西:

One way to solve this is to call the Invoke method of a control with a delegate to the function wich use the UI elements (like the message box). Somethin like:

public delegate void InvokeDelegate();

public void SomeMethod()
{

    button1.Invoke((InvokeDelegate)doUIStuff);


}


void doUIStuff()
{
           MessageBox.Show(this,   
                ex.Message, 
                "Error", 
                MessageBoxButtons.OK, 
                MessageBoxIcon.Error
            );
}

这篇关于Winforms线程问题,第二个线程无法访问第一个主窗体控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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