一、前言
本章只是我看教程学习的代码,仅仅作为自己使用的笔记。不做过多的介绍,毕竟我学得不精。
二、代码
本段代码的目标是实现,先输入1 ,在输出2.
1、使用 Task.Delay().Wait()
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// 函数调用学习 /// </summary> namespace ConsoleApp1 { class Program { static void Main(string[] args) { ///当前时间 var bt = DateTime.Now.Ticks; new Test().DoEvent(); Task.Delay(1).Wait(); Console.WriteLine(2); Console.ReadLine(); } } class Test { public void DoEvent() { var x = new Thread(new ThreadStart(() => { Console.WriteLine("1"); })); x.Start(); } } }
2、使用委托
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// 函数调用学习 /// </summary> namespace ConsoleApp1 { class Program { static void Main(string[] args) { ///当前时间 var bt = DateTime.Now.Ticks; new Test().DoEvent(() => { Console.WriteLine("2"); }); Console.WriteLine($"{ (double)(DateTime.Now.Ticks - bt) / (double)10_000}/ms"); Console.ReadLine(); } } class Test { public void DoEvent(Action action) { var x = new Thread(new ThreadStart(() => { Console.WriteLine("1"); action(); })); x.Start(); } } }
3、使用Task
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// 函数调用学习 /// </summary> namespace ConsoleApp1 { class Program { static void Main(string[] args) { ///当前时间 var bt = DateTime.Now.Ticks; new Test().DoEvent(); Console.WriteLine($"{ (double)(DateTime.Now.Ticks - bt) / (double)10_000}/ms"); Console.ReadLine(); } } class Test { public void DoEvent() { var t = new Task(() => { });//使用这样就可以先打印 1 在打印 2; var x = new Thread(new ThreadStart(() => { Console.WriteLine("1"); t.Start(); })); x.Start(); t.Wait(); } } }