您的位置:首页 > 编程语言 > C#

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());

}

}
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
寻找523 发布了2 篇原创文章 · 获赞 0 · 访问量 463 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: