用异步的方式调用同步方法
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 Test
{
class Program
{
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("异步调用后");
//方法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); //停止调用
}
public void move()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("异步任务执行");
Thread.Sleep(1000);
}
}
public void tellyou(IAsyncResult result)//回调函数
{
AsyncResult asyncResult = result as AsyncResult;
mydelegate mydelegate = asyncResult.AsyncDelegate as mydelegate;
mydelegate.EndInvoke(result);
if (result.IsCompleted)
{
Console.WriteLine("异步任务完成");
}
}
static void Main(string[] args)
{
Program pr = new Program();
Console.WriteLine("开始执行..");
pr.smork();
Thread.Sleep(1000);//注释掉结果有点不同
Console.WriteLine("我是主线程");
Console.ReadLine();
}
}
}