您的位置:首页 > 其它

BeginInvoke四种异步调用学习体会

2007-05-29 16:04 337 查看
以下内容摘之于MSDN,并结合自己加一些自己的看法:我学得这可以让让想了解用BeginInvoke来进生异步调用的人会有一个全面的了解:

进行某些操作,然后调用 EndInvoke 一直阻塞到调用完成。
使用 IAsyncResult.AsyncWaitHandle 获取 WaitHandle,使用它的 WaitOne 方法将执行一直阻塞到发出 WaitHandle 信号,然后调用 EndInvoke
轮询由 BeginInvoke 返回的 IAsyncResult,确定异步调用何时完成,然后调用 EndInvoke
将用于回调方法的委托传递给 BeginInvoke。该方法在异步调用完成后在 ThreadPool 线程上执行,它可以调用 EndInvoke
我觉得所为的异步调用是通过1.Thread.Sleep(),来控制主线程与BenginInovke线程的执行先后顺序.
2.通过EndInvoke来阻塞让线程,让BeginInvoke线程来执行.
3.回调方法无论如何都是要等等BeginInvoke所代理的方法先执行完,它才会执行.但,它们用的都是BeginInvoke 的线程;
   如果去掉上面的条件,那么就变成同步调用啦.

以下提代码测试:

using System;
using System.Threading;
//公共测试类
//使用 EndInvoke 等待异步调用测试主类

//使用 WaitHandle 等待异步调用测试主类

//轮询异步调用完成测试主类

//异步调用完成时执行回调方法测试主类
public class AsyncMain // Asynchronous method puts the thread id here.
private static int threadId;

static void Main(string[] args) // Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();

// Create the delegate.
AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);

// Initiate the asychronous call. Include an AsyncCallback
// delegate representing the callback method, and the data
// needed to call EndInvoke.
IAsyncResult ar = dlgt.BeginInvoke(3000,
out threadId,
new AsyncCallback(CallbackMethod),
dlgt );

Console.WriteLine("Press Enter to close application.");
Console.ReadLine();
}

// Callback method must have the same signature as the
// AsyncCallback delegate.
//下面那个回调方法,只有等到BeginInvoke所调用的代理方法执行完毕才会执行,但它们用的是同一条线程,而不是与主线程相同.
static void CallbackMethod(IAsyncResult ar) // Retrieve the delegate.
AsyncDelegate dlgt = (AsyncDelegate) ar.AsyncState;

// Call EndInvoke to retrieve the results.
string ret = dlgt.EndInvoke(out threadId, ar);

Console.WriteLine("The call executed on thread {0}, with return value \" }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐