c# Invoke 与BeginInvoke 的用法转载+修改
2020-04-05 12:13
2747 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Threading; namespace BeginInvokeEndInvoke { class Program { //定义了一个委托 public delegate string AsyncMethodCaller(int a, out int b); static void Main(string[] args) { AsyncMethodCaller caller = new AsyncMethodCaller(TestMethodAsync); // caller 为委托函数 int threadid = 0; /* 开启异步操作 * 这里要提示的是IAsyncResult result = caller.BeginInvoke(1000, out threadid, null, null);调用 * 了BeginInvoke后,主线程继续跑,同时也开始同时执行 * result = caller.BeginInvoke(1000, out threadid, null, null);异步的一系列操作 * 用result.IsCompleted来判断异步调用是否完成,完成了等于true,没完成等于flase * 面的第一行代码“Stopwatch sw = new Stopwatch();”,这个时候才会满足result.IsCompleted == false这个条件 * 用string res = caller.EndInvoke(out threadid, result);方法获取异步调用的后生成的结果out threadid * 最后 result.AsyncWaitHandle.Close();,释放AsyncWaitHandle该异步句柄所有资源 * **************************************************************/ IAsyncResult result = caller.BeginInvoke(1000, out threadid, null, null); for (int i = 0; i < 10; i++) { Console.WriteLine("其它业务" + i.ToString()); } //调用EndInvoke,等待异步执行完成 Console.WriteLine("等待异步方法TestMethodAsync执行完成"); //等待异步执行完毕信号 //result.AsyncWaitHandle.WaitOne(); //Console.WriteLine("收到WaitHandle信号"); //通过循环不停的检查异步运行状态 while (result.IsCompleted == false) { Thread.Sleep(100); Console.WriteLine("异步方法,running........"); } //异步结束,拿到运行结果 string res = caller.EndInvoke(out threadid, result); //显示关闭句柄,AsyncWaitHandle资源 result.AsyncWaitHandle.Close(); Console.WriteLine("TestMethodAsync:{0}", res); Console.WriteLine("关闭了WaitHandle句柄"); Console.ReadKey(); } /// <summary> /// 测试异步方法 /// </summary> /// <param name="callDuration">持续时间</param> /// <param name="threadId"></param> /// <returns></returns> static string TestMethodAsync(int callDuration, out int threadId) { //System.Diagnostics. Stopwatch提供一组方法和属性,准确地测量运行时间 Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("异步TestMethodAsync开始"); for (int i = 0; i < 5; i++) { // 模拟耗时操作 Thread.Sleep(callDuration); Console.WriteLine("TestMethodAsync:" + i.ToString()); } sw.Stop(); threadId = Thread.CurrentThread.ManagedThreadId; return string.Format("耗时{0}ms.", sw.ElapsedMilliseconds.ToString()); } } }
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【转载】C#线程系列讲座(1):BeginInvoke和EndInvoke方法
- C#中BeginInvoke和EndInvoke的用法
- 转载:C# this.Invoke()的作用与用法 理解三
- C# this.Invoke()的作用与用法
- Func和Action的用法,BeginInvoke和Invoke的使用
- C#之begininvoke和endinvoke
- C# this.Invoke()的作用与用法
- c# Winform Invoke 的用法
- C#中Invoke和BeginInvoke的区别
- c# Invoke和BeginInvoke 区别
- 转载:C# HashSet 用法
- C#线程系列讲座(1):BeginInvoke和EndInvoke方法
- C# 中virtual,override,new 的区别与用法(转载)
- C#线程系列讲座(1):BeginInvoke和EndInvoke方法
- (转载的)C#using的用法
- C# invoke和begininvoke
- C#线程系列讲座(1):BeginInvoke和EndInvoke方法
- 【转】C#中Invoke的用法
- [上传下载] C#修改DownLoadHelper上传下载帮助类 (转载)
- c# Invoke和BeginInvoke 区别