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
總結
以上是生活随笔為你收集整理的C# thread和delegate lambda函数结合的一段code的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NOIP2017提高组模拟赛4 (总结)
- 下一篇: C#语言实例源码系列-自定义ListBo