一个C#简单事件代理

原创
2016/12/10 22:12
阅读数 62

C#

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

namespace CSharp1
{
    public delegate void MessageHandler(string messageText);
    class Connection
    {
        public event MessageHandler MessageArrived;
        private Timer pollTimer;
        public Connection()
        {
            pollTimer = new Timer(100);
            pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);
        }
        private void CheckForMessage(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("Check for new messages.");
            Random random = new Random();
            if ((random.Next(9) == 0) && (MessageArrived != null))
            {
                MessageArrived("Hello Mami!");
            }
        }
        public void Connect() => pollTimer.Start();
        public void DisConnect() => pollTimer.Stop();
    }
    class Display
    {
        public void DisplayMessage(string mess) => Console.WriteLine($"Message arrived: {mess}");
        
        
    }
}


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

namespace CSharp1
{
    class Program
    {
        static int counter = 0;
        static string displayString = "This string will appear one letter at a time.";

        static void Main(string[] args)
        {
            Connection conn = new Connection();
            Display dis = new Display();
            conn.MessageArrived += new MessageHandler(dis.DisplayMessage);
            conn.Connect();

            Console.ReadKey();
            conn.DisConnect();
            Console.ReadKey();
        }



    }
}


展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部