[C#] 非同步的Task & Reflection動態呼叫方法

如標題 參考了下面作者的內容

 

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadDORUN("1");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ThreadDORUN("2");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ThreadDORUN("3");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ThreadDORUN("4");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            ThreadDORUN("5");
        }

        // https://stackoverflow.com/questions/5983779/catch-exception-that-is-thrown-in-different-thread
        // https://stackoverflow.com/questions/5209591/are-tasks-created-as-background-threads
        // https://dotblogs.com.tw/kinanson/2017/05/03/075119
        // https://vulcanlee.gitbooks.io/csharp2019/content/Part1/Task-DORUN-Factory-StartNew-ThreadPool-Thread-SetMinThreads.html
        // https://www.huanlintalk.com/2013/01/aspnet-45-fire-and-forget-async-call.html
        // https://www.huanlintalk.com/2013/06/csharp-notes-multithreading-6-tpl.html
        // https://dotblogs.com.tw/jesperlai/2018/04/06/013332                       

        private void ThreadDORUN(string v)
        {                      
                switch (v)
                {
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                        BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
                        MethodInfo method = this.GetType().GetMethod("DORUN" + v.PadLeft(2, '0'), flag);
                        //if (method != null)
                        //{                       
                        //    Thread oThread = new Thread(threadMain);
                        //    oThread.IsBackground = true;
                        //    oThread.Start();
                        //}
                        Task t = new Task(delegate () { method.Invoke(this, null); });
                        t.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
                        t.Start();                    
                    break;
                }
        }

        private delegate void UpdateUI(string str, Control ctl); //宣告委派

        private void updateText(string str, Control ctl)
        {
            if (this.InvokeRequired)
            {
                UpdateUI uu = new UpdateUI(updateText);
                this.Invoke(uu, str, ctl);
            }
            else
            {
                if (ctl is TextBox)
                {
                    TextBox txt = (TextBox)ctl;
                    txt.Text = str;
                }
                else if(ctl is Label)
                {
                    Label lab = (Label)ctl;
                    lab.Text = str;
                }
                //ctl.text = str;
            }
        }


        private void ExceptionHandler(Task task)
        {
            var exception = task.Exception;
            string txt = "";
            foreach (var item in task.Exception.InnerExceptions)
            {
                txt += item.InnerException.Message + ",";
            }


            updateText(txt, label6);

            //  MessageBox.Show( task.Exception.InnerExceptions.FirstOrDefault().Message);
            //  Console.WriteLine(exception);
        }

        private void DORUN01() {
            
            updateText("我被執行了DORUN01", label1);                        
           Thread.Sleep(2000);
            updateText("", label1);

        }
        private void DORUN02()
        {
            updateText("我被執行了DORUN02", label2);
            int a = 0;

            int b = 100 / a;
            //Thread.Sleep(2000);
            //   Thread.Sleep(2000);

            updateText("", label2);
        }
        private void DORUN03()
        {
            updateText("我被執行了DORUN03", label3);
            Thread.Sleep(2000);
            updateText("", label3);
        }
        private void DORUN04()
        {
            updateText("我被執行了DORUN04", label4);
            Thread.Sleep(2000);
            updateText("", label4);
        }
        private void DORUN05()
        {
            updateText("我被執行了DORUN05", label5);
            Thread.Sleep(2000);
            updateText("", label5);
        }
    }
}

 

namespace WindowsFormsApp1
{
    partial class Form1
    {
        /// <summary>
        /// 設計工具所需的變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清除任何使用中的資源。
        /// </summary>
        /// <param name="disposing">如果應該處置受控資源則為 true,否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 設計工具產生的程式碼

        /// <summary>
        /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改
        /// 這個方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(47, 53);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(47, 107);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 1;
            this.button2.Text = "button2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(47, 163);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 23);
            this.button3.TabIndex = 2;
            this.button3.Text = "button3";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // button4
            // 
            this.button4.Location = new System.Drawing.Point(47, 228);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(75, 23);
            this.button4.TabIndex = 3;
            this.button4.Text = "button4";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.button4_Click);
            // 
            // button5
            // 
            this.button5.Location = new System.Drawing.Point(47, 299);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(75, 23);
            this.button5.TabIndex = 4;
            this.button5.Text = "button5";
            this.button5.UseVisualStyleBackColor = true;
            this.button5.Click += new System.EventHandler(this.button5_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("新細明體", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            this.label1.Location = new System.Drawing.Point(156, 53);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(64, 24);
            this.label1.TabIndex = 5;
            this.label1.Text = "label1";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("新細明體", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            this.label2.Location = new System.Drawing.Point(156, 103);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 24);
            this.label2.TabIndex = 6;
            this.label2.Text = "label2";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("新細明體", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            this.label3.Location = new System.Drawing.Point(156, 159);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(64, 24);
            this.label3.TabIndex = 7;
            this.label3.Text = "label3";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("新細明體", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            this.label4.Location = new System.Drawing.Point(156, 228);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(64, 24);
            this.label4.TabIndex = 8;
            this.label4.Text = "label4";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Font = new System.Drawing.Font("新細明體", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            this.label5.Location = new System.Drawing.Point(156, 299);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(64, 24);
            this.label5.TabIndex = 9;
            this.label5.Text = "label5";
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.Font = new System.Drawing.Font("新細明體", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            this.label6.Location = new System.Drawing.Point(43, 352);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(64, 24);
            this.label6.TabIndex = 10;
            this.label6.Text = "label6";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(499, 446);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button5);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            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.Button button2;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
    }
}

 

參考來源 感謝下方作者

https://stackoverflow.com/questions/5983779/catch-exception-that-is-thrown-in-different-thread
https://stackoverflow.com/questions/5209591/are-tasks-created-as-background-threads
https://dotblogs.com.tw/kinanson/2017/05/03/075119
https://vulcanlee.gitbooks.io/csharp2019/content/Part1/Task-DORUN-Factory-StartNew-ThreadPool-Thread-SetMinThreads.html
https://www.huanlintalk.com/2013/01/aspnet-45-fire-and-forget-async-call.html
https://www.huanlintalk.com/2013/06/csharp-notes-multithreading-6-tpl.html
https://dotblogs.com.tw/jesperlai/2018/04/06/013332               

以上文章僅用紀錄資料使用.....