基于使用BeginInvoke,EndInvoke异步调用委托的实现代码
- 作者: 日骆希珊
- 来源: 51数据库
- 2021-10-19
复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
namespace consoleapplication1
{
class program
{
static void main(string[] args)
{
console.writeline("main threadid = " + thread.currentthread.managedthreadid);
//给委托赋值
func<long, long> delegatemethod = new func<long, long>(calcsum);
//异步执行委托,这里把委托本身作为asyncstate对象传进去,在回调函数中需要使用委托的endinvoke来获得结果
delegatemethod.begininvoke(200, donecallback, delegatemethod);
//异步执行委托,抛出异常
delegatemethod.begininvoke(10000000000, donecallback, delegatemethod);
console.readline();
}
//委托回调函数
static void donecallback(iasyncresult asyncresult)
{
//到这儿委托已经在异步线程中执行完毕
console.writeline("donecallback threadid = " + thread.currentthread.managedthreadid);
func<long, long> method = (func<long, long>)asyncresult.asyncstate;
//委托执行的异常会在endinvoke时抛出来
try {
//使用begininvoke时传入委托的endinvoke获得计算结果,这时候计算结果已经出来了,有异常的话也在这儿抛出来
long sum = method.endinvoke(asyncresult);
console.writeline("sum = {0}",sum);
}
catch (overflowexception)
{
console.writeline("运算溢出了");
}
}
//委托方法
static long calcsum(long toplimit)
{
//委托在另一个线程中开始执行
console.writeline("calc threadid = " + thread.currentthread.managedthreadid);
checked
{
long result = 0;
for (long i = 0; i < toplimit; i++)
{
result += i;
}
return result;
}
}
}
}
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0