浅谈AsyncState与AsyncDelegate使用的异同(转)
转自https://blog.csdn.net/zzy7075/article/details/51023433,仅供学习参考
对于AsyncState来说,其MSDN的解释为:得到BeginInvoke方法的最后一个参数。而对于AsyncDelegate来说,其MSDN的解释为:得到异步调用的委托对象。也就是异步调用的委托源。
对于委托的异步调用来说,其BeginInvoke函数无非包括以下内容,BeginInvoke(调用参数,回调函数,Object对象)
如果想利用AsyncState来还原对象的话,这里的Object对象必须是源委托;如果利用AsyncDelegate的话,这里可以为空,可以为源委托。具体区别请看下面的例子:
//AsyncState方式还原委托对象 chatDelegate.BeginInvoke(this, e, new AsyncCallback((iar) => { ChatDelegate thisDelegate = (ChatDelegate)iar.AsyncState; thisDelegate.EndInvoke(iar); }), chatDelegate); //AsyncDelegate方式还原委托对象 chatDelegate.BeginInvoke(this, e, new AsyncCallback((iar) => { AsyncResult ar = (AsyncResult)iar; ChatDelegate thisDelegate = (ChatDelegate)ar.AsyncDelegate; thisDelegate.EndInvoke(iar); }), null);
可以看到,当利用AsyncState时候,最后一个对象必须为源委托;当利用AsyncDelegate的时候,最后一个对象可以为null.
全部代码如下:
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate void ChatDelegate(object sender, MyEventArgs e); private static event ChatDelegate ChatEvent; private void Form1_Load(object sender, EventArgs e) { MyEventArgs myEventArgs = new MyEventArgs(); myEventArgs.Message = "this is test args"; ChatEvent+=new ChatDelegate(Form1_ChatEvent); ThrowEvent(myEventArgs); } private void Form1_ChatEvent(object sender, MyEventArgs e) { MessageBox.Show(e.Message); } private void ThrowEvent(MyEventArgs e) { ChatDelegate tempDelegate = ChatEvent; if(tempDelegate != null) { foreach (ChatDelegate chatDelegate in tempDelegate.GetInvocationList()) { //AsyncState方式还原委托对象 chatDelegate.BeginInvoke(this, e, new AsyncCallback((iar) => { ChatDelegate thisDelegate = (ChatDelegate)iar.AsyncState; thisDelegate.EndInvoke(iar); }), chatDelegate); //AsyncDelegate方式还原委托对象 //chatDelegate.BeginInvoke(this, e, new AsyncCallback((iar) => //{ // AsyncResult ar = (AsyncResult)iar; // ChatDelegate thisDelegate = (ChatDelegate)ar.AsyncDelegate; // thisDelegate.EndInvoke(iar); //}), null); } } } } public class MyEventArgs : EventArgs { public string Message { get; set; } } }