zoukankan
html css js c++ java
异步方式调用同步方法
一段异步方式调用同步方法代码
执行顺序 执行主程序>>执行异步调用>>执行
WaitOne()后代码>>执行回调>>执行主程序
using
System.Text;
using
System.Data;
using
System.Data.SqlClient;
using
System.Collections;
using
System.Threading;
using
System.IO;
using
System.Runtime.InteropServices;
using
System;
using
System.Runtime.Remoting.Messaging;
namespace
Program
{
public
class
Programmers
{
public
static
void
Main(
string
[] args)
{
Programmers pr
=
new
Programmers();
Console.WriteLine(
"
开始执行
..
"
);
pr.smork();
Thread.Sleep(
1000
);
//
注释掉结果有点不同
Console.WriteLine(
"
我是主线程
"
);
Console.ReadLine();
}
delegate
void
mydelegate();
private
void
smork()
{
/**/
///
异步方式调用同步方法1
AsyncCallback mycallback
=
new
AsyncCallback(tellyou);
//
(回调函数)
mydelegate mdg
=
new
mydelegate(move);
IAsyncResult result
=
mdg.BeginInvoke(mycallback,
null
);
result.AsyncWaitHandle.WaitOne();
//
等待异步完成
Console.WriteLine(
"
异步调用后
"
);
MyRegion
#region
MyRegion
//
异步方式调用同步方法2
//
AsyncCallback mycallback = new AsyncCallback(tellyou);
//
mydelegate mdg = new mydelegate(move);
//
IAsyncResult result = mdg.BeginInvoke(mycallback, null);
//
while (!result.IsCompleted)
//
{
//
//
Thread.Sleep(50);
//
不要与要有区别
//
}
/**/
///
/ 异步方式调用同步方法3(没有回调函数)
//
mydelegate mdg = new mydelegate(move);
//
IAsyncResult result = mdg.BeginInvoke(null, null);
//
while (!result.IsCompleted)
//
{
//
//
Thread.Sleep(60);
//
}
//
mdg.EndInvoke(result);
//
停止调用
//
异步方式调用同步方法4(没有回调函数)
//
mydelegate mdg = new mydelegate(move);
//
IAsyncResult result = mdg.BeginInvoke(null, null);
//
result.AsyncWaitHandle.WaitOne();
//
mdg.EndInvoke(result);
//
停止调用
#endregion
}
public
void
move()
{
for
(
int
i
=
0
; i
<
5
; i
++
)
{
Console.WriteLine(
"
异步任务执行
"
);
Thread.Sleep(
1000
);
}
}
public
void
tellyou(IAsyncResult result)
//
回调函数
{
//
Console.WriteLine("异步任务完成");
//
当异步完成后输出结果 通知已经异步完了
AsyncResult asyncResult
=
result
as
AsyncResult;
mydelegate mydelegate
=
asyncResult.AsyncDelegate
as
mydelegate;
mydelegate.EndInvoke(result);
if
(result.IsCompleted)
{
Console.WriteLine(
"
异步任务完成
"
);
}
}
}
}
查看全文
相关阅读:
6.12
20121006晴
6.11
测试利器IL级别的Debug工具“Deblector1.1.1修改版”
Windows Phone开发经验谈(15)动态的改变APP的字体大小
windows8开发直播windows8商店开发者帐号注册过程(完)
Windows Phone开发经验谈(13)华为网盘直链API调用
windows8开发App审核折腾记
Asp.net开发经验利用Aspose.Words按模板导出Word
Windows Phone开发经验谈(17)两则改善用户体验的开发技巧
原文地址:https://www.cnblogs.com/xiaobaigang/p/927920.html
最新文章
建立Silverlight 4安装环境
可遇不可求的Question之Php调用WebService传递时间参数篇
Blend4精选案例图解教程(四):请给我路径指引
Blend4精选案例图解教程(二):找张图片玩特效
Blend4精选案例图解教程(一):丰富的形状(Shape)资源
Blend4精选案例图解教程(三):一键拖拽
java内存分配与管理
Java继承中父类和子类的加载顺序
数据结构与算法(JAVA篇)一
Java里如何应用Json格式数据
热门文章
Eclipse插件安装maven svn ibatis openExplorer PropertiesEditor
Java继承
ATG技术架构概述
【转】ATG部分资源网站
java中代码覆写注意的问题
Java抽象类和接口的区别(好长时间没看这种文章了)
如何获取DOM中当前获取焦点的元素 Breaker
input text的事件收集 Breaker
SQLite的事务处理方式
20120826 晴
Copyright © 2011-2022 走看看