天天看点

C#委托调用过程(实例)

step 1. A类建立事件与事件函数

public event Func<string> GetSNEvent;
        public virtual string OnGetSNEvent()
        {
            return GetSNEvent?.Invoke();
        }
           

step 2. 类库C (dll)中建立函数(此处为控件dll)

public string getSN()
        {
            if (txtSN.InvokeRequired)// 此dll需要用到UI 为了跨线程访问不卡UI所以使用InvokeRequired
            {
                return (string)txtSN.Invoke(new Func<string>(getSN));
            }
            else
            {
                return txtSN.Text;
            }
        }
           
C#委托调用过程(实例)

step 3. 主UI线程(B线程)初始化时先绑定A线程的事件与dll (C)中函数之间关系:

burnProcess.GetSNEvent += burnInterface1.snInputBar1.getSN;
           

step 4. A线程中函数调用事件函数时就会触发事件去相应库C(dll)中相应的函数getSN()

private void OnCheckSN()
        {
           SN = OnGetSNEvent();
        }