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

发布于:2022-12-16 ⋅ 阅读:(346) ⋅ 点赞:(0)

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

首先是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

本文含有隐藏内容,请 开通VIP 后查看