C#延遲執行 1.0版本


涉及的知識有泛型,委托,多線程

實現了延遲執行一個函數,可以指定延遲時間,延遲的方法,實際是對異步編程的一個練習

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace WindowsFormsApplication1
{
    class DelayClass<T>
    {
      //  public Func<T> action;
       // public void DelayClass<T>(int i,Func<T> action){
       //     //setPara(i,action);
            
       //}
      
        
        private int time { get; set; }//延遲時間
        private T resualt { get;set;}//返回值

        private Func<T> func;//傳入函數
        private T delay(int j,Func<T> action) {///實現函數的運行
            T s=default(T);           
            if (action != null) {                       
               s= action();
            }
            return s;
        }
        private void delayme() {
            
            Thread delayThread = new Thread(new ThreadStart(delayDel));//新建一個線程來運行執行延遲時間
            delayThread.Start();
            
        }
        private void delayDel() { //延遲執行的作用
            int i=0;
            while (i < time) {
                i++;
                Thread.Sleep(1000);
            }
           resualt = delay(time, func);
           if (gs != null) {//委托傳值,當線程延遲time時間后執行返回值,相當於一個事件
               gs(resualt);
           }
        }

        public void runthisFunc(int i,Func<T> action) {//設置該類的基本參數,傳入時間和方法
            time = i;
          func = action;

        delayme();
        }
        public delegate void getresult(T result);//委托傳值定義
        public getresult gs;

    }
}
 

基本的原理是利用泛型委托傳入需要的參數,用一個新建線程延遲執行,執行完函數用委托做返回值

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            DelayClass<string> dclass = new DelayClass<string>();         
           
            dclass.setPara(4,actionme);
            dclass.gs = gss;

            
        }
        public string actionme() {
            return "this has wait for 4 s";
        }
        private void gss(string ss) {//接受傳回的值,並顯示
            label1.Invoke(setlabedel, ss);//do something alse
        }
        private Action<string> setlabedel;//定義委托,線程不能訪問UI
        private void setlable(string ss) { 
            label1.Text=ss;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            setlabedel = setlable;
        }
    }
}

使用的時候實例化類,傳入時間和方法。並實現該類的委托方法,即可調用該方法。

初步實現還需要很多更改,歡迎指正


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM