从WinForms应用程序中的另一个线程访问由GUI Worker Thread创建的Button

kar*_*tal 1 c# multithreading winforms

从C# - windows窗体应用程序中的不同线程访问GUI工作线程中创建的按钮

Jon*_*eet 6

如果您使用的是Windows窗体,通常需要使用Control.BeginInvokeControl.Invoke.

如果您正在使用WPF,则需要使用相应的Dispatcher并再次使用其BeginInvokeInvoke方法.

(基本上Invoke会阻塞,直到委托在正确的线程中执行; BeginInvoke不会.)

另一种选择是使用BackgroundWorker,但除非您只是报告进度,否则我倾向于使用上述选项之一.


Jim*_*ins 5

这是一个可以用来设置另一个线程的属性的函数:

using System.Reflection;
Run Code Online (Sandbox Code Playgroud)

...

    delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
    private void SetControlPropertyValue(Control oControl, string propName, object propValue)
    {
        if (oControl.InvokeRequired)
        {
            SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
            oControl.Invoke(d, new object[] { oControl, propName, propValue });
        }
        else
        {
            Type t = oControl.GetType();
            PropertyInfo[] props = t.GetProperties();
            foreach (PropertyInfo p in props)
            {
                if (p.Name.ToUpper() == propName.ToUpper())
                {
                    p.SetValue(oControl, propValue, null);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

示例用法

SetControlPropertyValue(Button1, "Enabled", false);
Run Code Online (Sandbox Code Playgroud)