C# event

C# event

https://www.youtube.com/watch?v=jQgwEsJISy0&t=1137s

ugly code myself

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 WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public delegate void CountEventHandler(object source, EventArgs args);  // 1- define the delegate
        public event CountEventHandler count;                                   // 2- define the event based on that delegate

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool flag = true;
            int i = 0;

            CountService countService = new CountService();
            this.count += countService.OnCount;

            while (flag)
            {
                i += 1;
                DateTime Tthen = DateTime.Now;
                do
                {
                    Application.DoEvents();
                } while (Tthen.AddSeconds(1) > DateTime.Now);

                if (i == 5)
                {
                    flag = false;
                    OnCount();
                }
            }

        }

        protected virtual void OnCount()                  // 3- raise the event
        {
            if (count != null)
                count(this, EventArgs.Empty);
        }

    }


    public class CountService
    {
        public void OnCount(object source,EventArgs e)
        {
            MessageBox.Show("Hi, the Count is 5 now");
            
        }
    }

}

猜你喜欢

转载自blog.csdn.net/honk2012/article/details/81605562