其他分享
首页 > 其他分享> > 跨线程UI组件调用

跨线程UI组件调用

作者:互联网

这是处理跨线程操作的适当方法吗?

我应该使用一个新的属性名称,例如“ EditValueThreadSafe”,而不是覆盖“ EditValue”吗?我认为对EditValue的实现所做的更改没有问题,因为无论如何都会调用base属性.

namespace MyApplication.Components
{
    using System.Windows.Forms;

    /// <summary>
    /// Thread-safe implementation of the DevExpress.XtraEditors.ComboBoxEdit class.
    /// </summary>
    public class ComboBoxEditThreadSafe : DevExpress.XtraEditors.ComboBoxEdit
    {
        /// <summary>
        /// Gets or sets the edit value.
        /// </summary>
        /// <value>The edit value.</value>
        public override object EditValue
        {
            get
            {
                return base.EditValue;
            }

            set
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.SetEditValue(value);
                    }));
                }
                else
                {
                    this.SetEditValue(value);
                }
            }
        }

        /// <summary>
        /// Sets the edit value.
        /// </summary>
        /// <param name="value">The value.</param>
        private void SetEditValue(object value)
        {
            base.EditValue = value;
        }
    }
}

解决方法:

您还可以委派另一个工作的方法,在该方法中,如果在错误的线程上(BeginInvoke返回true),然后再次调用相同的方法.这样做消除了重复代码的需要.

public class ComboBoxEditThreadSafe : DevExpress.XtraEditors.ComboBoxEdit    
{       
   public override object EditValue        
   {            
       get            
       {                             
            return base.EditValue;            
       }            
       set  
       {                
         SetValue(value);
       }
   }



    private void delegate SetValueDlg(object valeu);
    private void SetValue(object value)
    {
        if (this.InvokeRequired)
             this.BeginInvoke(
                 (SetValueDlg)SetValue,  // calls itself, but on correct thread
                 new object[] { value });
        else

              base.editValue = value;  

    }
}

您还可以使用Action()泛型类来消除创建显式委托类的需要.

   public class ComboBoxEditThreadSafe : DevExpress.XtraEditors.ComboBoxEdit    
{       
   public override object EditValue        
   {            
       get {  return base.EditValue;   }            
       set { SetValue(value); }
   }

   private void SetValue(object value)
   {
       if (this.InvokeRequired)
           this.BeginInvoke(
               new Action<object>(SetValue),  // calls itself, but on correct thread
               new object[] { value });
       else                
              base.editValue = value;  

   }

}

标签:multithreading,devexpress,c
来源: https://codeday.me/bug/20191210/2102152.html