C# 使用委托开始线程

编程入门 行业动态 更新时间:2024-10-19 17:21:39

C# 使用委托开始<a href=https://www.elefans.com/category/jswz/34/1771240.html style=线程"/>

C# 使用委托开始线程

使用委托的形式,调用线程,,,

using System;
using System.Threading;namespace _012_线程
{class Program{static void Main(string[] args) //在mian中线程是执行一个线程里面的语句的执行,是从上到下的{//通过委托 开启一个线程//==============可用泛型传参数(无返回值)==============Action threaA = ThreadTestA;threaA.BeginInvoke(null,null);  //开启一个新的线程去执行,threaA所引用的方法Action<int> threaB = ThreadTestB;threaB.BeginInvoke(111,null, null);//可以认为线程是同时执行的 (异步执行)Console.WriteLine("异步执行");//================带返回值的形式====================//第一种方式  检测线程结束   ----- IsCompleted线程是否行完毕//Func<int, int> threaC = ThreadTestC;////接收异步线程返回值//IAsyncResult returnResult = threaC.BeginInvoke(111, null, null);//while (!res.IsCompleted)//{//    Console.Write(".");//    Thread.Sleep(10); //控制子线程的检测频率,(每10ms检测一次)//}////取得异步线程返回值//int result = threaC.EndInvoke(res);//Console.WriteLine("IsCompleted方式检测:" + result);//第二种方式  检测线程结束   -----   1000ms没结束就返回false,反之Func<int, int> threaC = ThreadTestC;//接收异步线程返回值IAsyncResult returnResult = threaC.BeginInvoke(111, null, null);bool isEnd = returnResult.AsyncWaitHandle.WaitOne(1000);int result = 0;if (isEnd){result = threaC.EndInvoke(returnResult);}Console.WriteLine("EndInvoke()方式检测:" + isEnd +"  "+ result);//第三种方式   检测线程结束   -----  通过回调,检测线程结束Func<int,string, string> threaD = ThreadTestD;//倒数第二个参数,表示委托类型的参数,(回调函数)当线程结束的时候会调用这个委托指向的方法//最后一个参数,用来给回调函数传递数据IAsyncResult asy = threaD.BeginInvoke(111,"Czhenya", OnCallKey, threaD);//改为Lamdba表达式threaD.BeginInvoke(111, "Czhenya",(ar)=>{string res = threaD.EndInvoke(ar);Console.WriteLine("在Lamdba表达式中取得:"+res);},null);Console.ReadKey();}static void OnCallKey(IAsyncResult ar){Func<int, string, string> thread = ar.AsyncState as Func<int, string, string>;string res = thread.EndInvoke(ar);Console.WriteLine("在回调函数中取到的结果 :"+res);}/// <summary>/// 一般是比较耗时的操作方法/// </summary>static void ThreadTestA(){Console.WriteLine("ThreaTestA");}static void ThreadTestB(int num){Console.WriteLine("ThreaTestB "+num);}static int ThreadTestC(int num){Console.WriteLine("ThreaTestC");Thread.Sleep(100);  //让当前线程休眠(暂停线程(参数单位:ms))return num;}static string ThreadTestD(int num,string str){Console.WriteLine("ThreaTestD");return num +" "+ str;}}
}

运行结果图:

更多推荐

C# 使用委托开始线程

本文发布于:2024-03-14 18:41:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1737098.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!