C# thread和delegate lambda函数结合的一段code

以下是一段经典代码,可供以后参考并使用

首先是cs类:

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

namespace EventDelegateTest1
{
    class MyTimer
    {

        private bool flag1;
        private bool flag2;

        public bool Flag1 { get; set; }
        public bool Flag2 { get; set; }

        Thread thread1;
        public void startTimer1()
        {
            thread1 = new Thread(delegate () {
                double time = 0;
                while (Flag1 == true)
                {
                    Thread.Sleep(1000);
                    time++;
                    string timeTick = TimeSpan.FromSeconds(time).ToString(@"mm\:ss");
                    Console.WriteLine("current time is {0}",timeTick);
                }
            });
            thread1.IsBackground = true;
            thread1.Start();
        }

        Thread thread2;
        public void startTimer2()
        {
            thread2 = new Thread(delegate () {
                double time = 0;
                while (Flag2 == true)
                {
                    Thread.Sleep(1000);
                    time++;
                    string timeTick = TimeSpan.FromSeconds(time).ToString(@"mm\:ss");
                    Console.WriteLine("current time is {0}", timeTick);
                }
            });
            thread2.IsBackground = true;
            thread2.Start();
        }
    }
}
然后是main函数执行内容:

 static void Main(string[] args)
        {
            MyTimer mytimer = new MyTimer();
            mytimer.Flag1 = true;
            mytimer.startTimer1();
            Console.ReadKey();
        }

上面的code大致意思是delegate在C#中就是和lambda类似的功能

以下是例子:

delegate void StudentDelegate(string name, int age);
public class LambdaTest
{
    public void Show()
    {
        DateTime dateTime = DateTime.Now;
        //版本2(这样写的话可以访问局部变量)
        {
            StudentDelegate student = new StudentDelegate( delegate (string name, int age)
            {
                Console.Write(dateTime);
                Console.WriteLine($"我的名字是:{name},我的年龄是{age}");
            });
            student("王朝伟", 1);
        }
    }
}

什么是lambda表示式

Lambda 表达式是一种可用于创建委托或表达式目录树的匿名函数(摘自MSDN)这句话是什么意思下面慢慢开始说起

具体可以参考下博客:

C# Lambda的用法_忆水思寒的博客-CSDN博客_c# lambda

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值