class Program { static void Main(string[] args) { //线程 Thread tread = new Thread(new ThreadStart(new Action(() => { TestLock(); TestLock(); TestLock(); }))); tread.Start(); //线程 new Task(() => { new Action(() => { TestLock(); }).BeginInvoke(null, null); }).Start(); //异步函数 TestAsync(); Console.Write("haha"); Console.Read(); } //委托1 public delegate string TestDelegate(string a); /// <summary> /// 委托测试函数 /// </summary> public static string TestDelegateMe(string a) { return a ?? "a为空显示此语句!"; } /// <summary> /// 委托 /// </summary> public static void Delegate() { //BeginInvoke这种不会阻塞线程Invoke会阻塞 //异步委托1 TestDelegate del = new TestDelegate(TestDelegateMe); string te = del.EndInvoke(del.BeginInvoke("a的值", null, null)); //异步委托2 var action = new Action(() => { TestLock(); }); action.EndInvoke(action.BeginInvoke(null, null)); //线程+异步委托3 new Task(() => { new Func<int>(() => { TestLock(); return 1; }).BeginInvoke(null, null);//线程异步有返回 new Action(() => { TestLock(); }).BeginInvoke(null, null);//线程异步无返回 TestLock();//线程同步 }).Start(); //线程 Thread tread = new Thread(new ThreadStart(TestLock)); tread.Start(); HttpClient client = new HttpClient(); client.PostAsync("", new MultipartFormDataContent() { new ByteArrayContent(System.Text.Encoding.Default.GetBytes("将要转换为字节的字符串")) }); } /// <summary> /// 异步函数 /// </summary> /// <returns>返回值只能是Task或者Task<T></returns> public static async void TestAsync() { await Task.Run(new Action(() => { TestLock(); })); } //资源锁 public static object obj = new object(); /// <summary> /// 资源锁的测试(用线程异步调用此函数) /// </summary> public static void TestLock() { //当obj资源被锁定,别的线程是无法调用的,所以必须等待此资源调用结束 lock (obj) { for (int i = 0; i < 2; i++) { Thread.Sleep(1000); Console.Write(i);//输出0-1/0-1 } } }
}