委托之异步多线程,解决参数传递和返回值问题

项目场景:

设计了一个交互界面,要求两个用户点击交互事件下面的耗时操作互不影响,不能阻塞UI线程,并且返回执行结果。
下面代码主要使用了BeginInvoke来实现。invoke和begininvoke网上的介绍也很多。这里就不一一介绍,推荐给大家一篇博文:invoke and begininvoke


问题描述:

一般线程是无参无返回值
Example:
Thread t = new Thread(new ThreadStart(MyFunction));
t.Start();
其中的MyFunction 是无参无返回值。
private void MyFunction()
{
}

有参的也只能传递obj的类型。
Example:
System.Threading.Thread td = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(MyFunction));
其中的MyFunction 是有参无返回值。
private void MyFunction(object sign)
{
}
这样写法在很多应用场景下面都不灵活,也不满足。

下面代码是利用委托来实现这个功能的demo。

1.委托代码,用户交互事件代码,功能性代码。

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public delegate bool Btn_ProcessMethod(int sign);//UI以外线程代理
        Btn_ProcessMethod ProcessMethod;//UI以外线程代理申明 
        public delegate void delegateAddDisplay(int sign);//显示textBox1信息委托
        public delegate void delegateEndDisplay(string str);//显示textBox2信息委托

        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = "";
       
            this.textBox2.Text = "";
            int startInt = 10;//从10开始加起
            ProcessMethod = new Btn_ProcessMethod(CallFun);
            ProcessMethod.BeginInvoke(startInt, new AsyncCallback(CallBackFun), null);
            


        }
      
        /// <summary>
        /// 委托调用的方法(主要是做一件事情;把textBox1中的数字加1加5次,返回事情已经做完的结果状态)
        /// </summary>
        /// <param name="sign"></param>
        /// <returns></returns>
        private bool CallFun(int sign)
        {
            int ReturnInt = 0;//返回加1的次数
            while (ReturnInt < 5)//加5次
            {
                sign++;
                if (this.InvokeRequired)//如果不是当前UI线程则返回true
                {
                    this.Invoke(new delegateAddDisplay(AddDisplay), sign);
                }
                else
                {
                    AddDisplay(sign);
                }
                ReturnInt++;
                System.Threading.Thread.Sleep(2000);//两秒加一次
            }
            return true;
        }
       
        private void AddDisplay(int sign)
        {
            this.textBox1.Text = sign.ToString();
        }
        private void EndDisplay(string str)
        {
            this.textBox2.Text = str;
        }
        /// <summary>
        /// 异步回调方法
        /// </summary>
        /// <param name="IAresult"></param>
        /// <returns></returns>
        public void CallBackFun(IAsyncResult IAresult)
        {
            bool ReturnBool = ProcessMethod.EndInvoke(IAresult);//得到CallFun方法的返回值
            if (ReturnBool)//CallFun方法返回True,说明CallFun方法已经执行完毕
            {
                if (this.InvokeRequired)//如果不是当前UI线程则返回true
                {
                    //因为textBox2是UI线程创建的控件,所以要判断当前是不是创建此控件的UI线程
                    //(不然,就出现你所说的错误:“ 线程间操作无效:从不是创建控件 的线程访问它”)
                    this.Invoke(new delegateEndDisplay(EndDisplay), "事情已经做完");
                }
                else
                {
                    EndDisplay("事情已经做完");
                }
            }
        }
       

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("你执行你的加法运算,我弹我的框,哈哈");
        }
    

2.设计器代码

     #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Text = "Form1";
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.button2 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(58, 119);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "start";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(128, 63);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 20);
            this.textBox1.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(55, 66);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(67, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "线程做加法";
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(287, 63);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(100, 20);
            this.textBox2.TabIndex = 3;
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(157, 119);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(240, 23);
            this.button2.TabIndex = 4;
            this.button2.Text = "执行start按钮期间,点击我弹Message";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(437, 249);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button button2;
    

3.用户界面

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值