WinForms 线程安全控制访问 [英] WinForms thread safe control access

查看:35
本文介绍了WinForms 线程安全控制访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试访问 WinForms 控件时,出现错误 从一个线程访问的控件,而不是它创建的线程.我知道控件的所有修改都应该在 UI 线程中执行(需要 BeginInvoke() 等),但我需要我的控件是只读的.

I get error Control accessed from a thread other than the thread it was created on when I try to access WinForms control. I know that all modifications of control should be performed in UI thread (requiring BeginInvoke(), etc.), but I need my control to be read only.

这是我的简化代码:

string text = textBox.Text;

从另一个线程访问 WinForms 控件的属性值的模式是什么?

What is the pattern for accessing WinForms control's properties values from another thread?

推荐答案

对于像这样微不足道的事情,您不必专门使用 BeginInvoke,您也可以使用 Invoke,但是您确实需要调用调用在 UI 线程上.您可以使用一些魔法来隐藏一些方法调用中令人讨厌的细节,然后使用扩展方法使其更清晰.例如,假设我想使用几个用于获取和设置 Text 属性的 theadsafe 方法来扩展 TextBox 控件.我可能会做这样的事情:

For something as trivial as this, you don't have to use BeginInvoke specifically, you could use Invoke as well, but yes you do need to invoke the call on the UI thread. You can use some magic to hide the nasty details in a couple method calls and then use extension methods to make it cleaner. For example, let says I wanted to extend the TextBox control with a couple theadsafe methods for getting and setting the Text property. I might do something like this:

namespace System.Windows.Forms
{
    public static class TextBoxExtensions
    {        
        public static string GetTextThreadSafe(this TextBox box)
        {
            return GetTextBoxText(box);
        }

        public static void SetTextThreadSafe(this TextBox box, string str)
        {
            SetTextBoxText(box, str);
        }

        public static string GetTextBoxText(TextBox box)
        {
            if (box.InvokeRequired)
            {
                Func<TextBox, string> deleg = new Func<TextBox, string>(GetTextBoxText);
                return box.Invoke(deleg, new object[] { box }).ToString();
            }
            else
            {
                return box.Text;
            }
        }

        public static void SetTextBoxText(TextBox box, string str)
        {
            if (box.InvokeRequired)
            {
                Action<TextBox, string> deleg = new Action<TextBox, string>(SetTextBoxText);
                box.Invoke(deleg, new object[] { box, str });
            }
            else
            {
                box.Text = str;
            }
        }
    }
}

然后在另一个线程中,您可以像这样调用文本框:

Then in another thread you could call the textbox like so:

Thread t = new Thread(new ThreadStart(() =>
{
    // Threadsafe call to set the text
    SomeTextBox.SetTextThreadSafe("asdf");
    // Threadsafe call to get the text
    MessageBox.Show(SomeTextBox.GetTextThreadSafe());                
}));
t.IsBackground = true;
t.Start();

这篇关于WinForms 线程安全控制访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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