C# 跨线程操作控件方法封装

Winform程序需要处理耗时操作时,往往需要将耗时操作放入新开的子线程进行处理,在子线程中可能会经常去修改或操作主线程上的控件;

如果直接在子线程中操作控件,会报线程间操作无效等错误,这里提供一个我自己经常使用的跨线程操作方式,代码如下:

        //跨线程操作控件
        //(将数据全部装填完毕后,在一起放到主界面刷新控件;不要一边装填一边刷新主界面控件,这样依然会导致界面卡顿)
        public void showMsg(string str)
        {
            if (textBox.InvokeRequired)
            {
                textBox.Invoke(new Action<string>((s) =>
                {
                    this.textBox.Text = s + "\r\n" + this.textBox.Text;
                }), str);
            }
            else
            {
                this.textBox.Text = s + "\r\n" + this.textBox.Text;
            }
        }

注意:将数据全部装填完毕后,在一起放到主界面刷新控件;不要一边装填一边刷新主界面控件,这样虽然主界面的窗体还能够移动,依然会导致界面卡顿以及其他控件响应延迟;

比如:在给ListView控件装填数据时,应先循环把数据全部装填在一个新建的ListView对象中,然后将新建的ListView对象中的数据利用上述代码循环拷贝到已有控件中;

以上是自己工作中使用的方法,如果有大神有更好的方法,希望能够回复,非常接受批评与指导!

 

以下记录一下,参考网上写的一个跨线程操作控件的封装类,具体如下:

主要为3个方法:Invoke,Get,Set;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Common
{
    /// <summary>
    /// 跨线程调用控件帮助类
    /// </summary>
    public class InvokeHelper
    {
        #region delegates  

        private delegate object MethodInvoker(Control control, string methodName, params object[] args);
        private delegate object PropertyGetInvoker(Control control, object noncontrol, string propertyName);  
        private delegate void PropertySetInvoker(Control control, object noncontrol, string propertyName, object value);
  
        #endregion  
  
        #region static methods  
        // helpers  
        private static PropertyInfo GetPropertyInfo(Control control, object noncontrol, string propertyName)  
        {
            if (control != null && !string.IsNullOrEmpty(propertyName))
            {
                PropertyInfo pi = null;
                Type t = null;

                if (noncontrol != null)
                    t = noncontrol.GetType();
                else
                    t = control.GetType();

                pi = t.GetProperty(propertyName);

                if (pi == null)
                    throw new InvalidOperationException(
                        string.Format(
                        "Can't find property {0} in {1}.",
                        propertyName,
                        t.ToString()
                        ));

                return pi;
            }
            else
            {
                throw new ArgumentNullException("Invalid argument.");
            }
        }  
   
        /// <summary>
        /// 调用主界面控件的某个方法,并返回方法执行结果
        /// </summary>
        /// <param name="control"> 控件 </param>
        /// <param name="methodName"> 方法名 </param>
        /// <param name="args"> 参数 </param>
        /// <returns></returns>
        public static object Invoke(Control control, string methodName, params object[] args)  
        {
            if (control != null && !string.IsNullOrEmpty(methodName))
            {
                if (control.InvokeRequired)
                {
                    return control.Invoke(
                        new MethodInvoker(Invoke),
                        control,
                        methodName,
                        args
                        );
                }
                else
                {
                    MethodInfo mi = null;

                    if (args != null && args.Length > 0)
                    {
                        Type[] types = new Type[args.Length];
                        for (int i = 0; i < args.Length; i++)
                        {
                            if (args[i] != null)
                                types[i] = args[i].GetType();
                        }

                        mi = control.GetType().GetMethod(methodName, types);
                    }
                    else
                        mi = control.GetType().GetMethod(methodName);

                    // check method info you get  
                    if (mi != null)
                        return mi.Invoke(control, args);
                    else
                        throw new InvalidOperationException("Invalid method.");
                }
            }
            else
            {
                throw new ArgumentNullException("Invalid argument.");
            }
        }  
   
        /// <summary>
        /// 获取主界面控件的某个属性
        /// </summary>
        /// <param name="control"> 控件 </param>
        /// <param name="propertyName"> 属性名 </param>
        /// <returns></returns>
        public static object Get(Control control, string propertyName)  
        {  
            return Get(control, null, propertyName);  
        }  

        public static object Get(Control control, object noncontrol, string propertyName)  
        {
            if (control != null && !string.IsNullOrEmpty(propertyName))
            {
                if (control.InvokeRequired)
                {
                    return control.Invoke(new PropertyGetInvoker(Get),
                        control,
                        noncontrol,
                        propertyName
                        );
                }
                else
                {
                    PropertyInfo pi = GetPropertyInfo(control, noncontrol, propertyName);
                    object invokee = (noncontrol == null) ? control : noncontrol;

                    if (pi != null)
                        if (pi.CanRead)
                            return pi.GetValue(invokee, null);
                        else
                            throw new FieldAccessException(
                                string.Format(
                                "{0}.{1} is a write-only property.",
                                invokee.GetType().ToString(),
                                propertyName
                                ));

                    return null;
                }
            }
            else
            {
                throw new ArgumentNullException("Invalid argument.");
            }
        }  
   
        /// <summary>
        /// 设置主界面控件的某个属性
        /// </summary>
        /// <param name="control"> 控件 </param>
        /// <param name="propertyName"> 属性名 </param>
        /// <param name="value"> 属性值 </param>
        public static void Set(Control control, string propertyName, object value)  
        {  
            Set(control, null, propertyName, value);  
        }  

        public static void Set(Control control, object noncontrol, string propertyName, object value)  
        {
            if (control != null && !string.IsNullOrEmpty(propertyName))
            {
                if (control.InvokeRequired)
                {
                    control.Invoke(new PropertySetInvoker(Set),
                        control,
                        noncontrol,
                        propertyName,
                        value
                        );
                }
                else
                {
                    PropertyInfo pi = GetPropertyInfo(control, noncontrol, propertyName);
                    object invokee = (noncontrol == null) ? control : noncontrol;

                    if (pi != null)
                        if (pi.CanWrite)
                            pi.SetValue(invokee, value, null);
                        else
                            throw new FieldAccessException(
                                string.Format(
                                "{0}.{1} is a read-only property.",
                                invokee.GetType().ToString(),
                                propertyName
                                ));
                }
            }
            else
            {
                throw new ArgumentNullException("Invalid argument.");
            }
        }  
        #endregion  
    }
}

 

转载于:https://www.cnblogs.com/stardust-dream/p/7815157.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C是计算机科学领域中的一门编程语言。它是由丹尼斯·里奇于20世纪70年代初在贝尔实验室开发的。C语言是一种通用的高级语言,被广泛用于操作系统、嵌入式系统、游戏开发等领域。 C语言具有许多优点。首先,它是一种结构化的编程语言,易于理解和学习。它使用简洁的语法和直观的控制结构,使得程序员可以快速编写高效的代码。其次,C语言具有高度的可移植性,可以在不同的计算机平台上运行。这一点对于开发平台应用程序非常重要。另外,C语言还具有丰富的库函数,使得开发人员可以方便地调用各种功能。 然而,C语言也存在一些缺点。首先,它相对于现代的高级语言来说比较低级。这意味着程序员需要花费更多的时间和精力来处理细节。其次,C语言的内存管理需要手动管理,这可能会导致内存泄漏和指针错误。最后,C语言对于错误处理相对较弱,需要程序员自己进行错误检查和处理。 总的来说,C语言是一门强大而灵活的编程语言,对于想要深入了解计算机底层工作原理的人来说是非常有价值的。它不仅为开发各种应用程序提供了丰富的功能和灵活性,还为学习其他高级编程语言打下了基础。虽然C语言在当前技术领域中已经有了其他更高级的替代品,但它作为计算机科学的基础语言仍然具有重要的地位。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值