异步委托线程补充
1: bool IAsyncResult.AsyncWaitHandle.waitone(1000)的使用
等待异步委托函数1000ms,在1000ms内接收到委托函数执行完的信息后,立即返回true,1000ms内未执行完返回false
class Program { static void Main(string[] args) { Thread thread = Thread.CurrentThread;//获取当前线程对象 Console.WriteLine(thread.ManagedThreadId);//打印出当前对象的id Func<int, int> a = test;//委托 IAsyncResult thread1 = a.BeginInvoke(1, null, null);//启动异步委托线程 bool istrue = thread1.AsyncWaitHandle.WaitOne(1000);//检测1000ms内异步委托线程是否结束 if (istrue)//结束打印aaa
{ Console.WriteLine("aaa"); } int value = a.EndInvoke(thread1);//获取异步委托线程的返回值 Console.WriteLine(value); Console.ReadKey(); } private static int test(int arg)//委托方法 { Thread thread = Thread.CurrentThread; Console.WriteLine(thread.ManagedThreadId); Thread.Sleep(1000);//本线程暂停1000ms return arg; }
2:异步委托的回调函数的参数问题
IAsyncResult al=委托.BeginInvoke(null,null)//nul前面是传委托的参数的,第一个null是指异步委托的回调函数,第二个null是回调函数的参数,这个null只能是引用类型在回调函数中用IAsyncResult.AsyncState获取这个参数,再转化为自生类型使用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace 异步委托实现线程 { class Program { static void Main(string[] args) { Func<int, int> a = test;//将test方法委托给a IAsyncResult thread1 = a.BeginInvoke(20, onCallBack, "string");//"string"作为回调函数的参数传入回调函数,onCallBack是回调函数 Console.ReadKey(); } private static int test(int arg) { Thread thread = Thread.CurrentThread; Console.WriteLine(thread.ManagedThreadId); Thread.Sleep(1000);//暂停本线程1000ms return arg; } /// <summary> /// 异步委托的回调函数 /// </summary> /// <param name="ar"></param> public static void onCallBack(IAsyncResult ar)//回调函数的参数是IAsyncResult ,将委托线程的状态传给回调函数 { string value = ar.AsyncState as string;//IAsyncResult.AsyncState是获取异步委托线程的第四个参数,将其转化为自生的类型 Console.WriteLine(value); } } }
3:异步委托的回调函数获取委托返回值的第二种方法:利用异步委托线程的第四个参数,直接把委托传入回调函数,再回调函数中用委托调用EndInvoke(IAsyncResult)获取委托函数的返回值
一般我们不再线程中获取另一个线程的返回值,因为如果另一个线程阻塞,则这个线程也会阻塞
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace 异步委托实现线程 { class Program { static void Main(string[] args) { Func<int, int> a = test;//将test方法委托给a IAsyncResult thread1 = a.BeginInvoke(20, onCallBack, a);//"string"作为回调函数的参数传入回调函数,onCallBack是回调函数 Console.ReadKey(); } private static int test(int arg) { Thread thread = Thread.CurrentThread; Console.WriteLine(thread.ManagedThreadId); Thread.Sleep(1000);//暂停本线程1000ms return arg; } /// <summary> /// 异步委托的回调函数 /// </summary> /// <param name="ar"></param> public static void onCallBack(IAsyncResult ar)//回调函数的参数是IAsyncResult ,将委托线程的状态传给回调函数 { Func<int, int> fun = ar.AsyncState as Func<int,int>;//IAsyncResult.AsyncState是获取异步委托线程的第四个参数,将其转化为自生的类型,这里传入的是委托函数,我们将它转化为原来的类型 int value = fun.EndInvoke(ar);//等待获取委托函数的返回值 Console.WriteLine(value); } } }