1.委托的異步使用BeginInvoke,這樣程序執行時不需要等待委托的函數執行完以后再執行下一句。
但是委托的異步如果有返回值
1 2 3 4 5 | PRivate delegate void invokeDelegate(); del = new invokeDelegate(StartMethod); var re= del.BeginInvoke( null , null ); MessageBox.Show( del.EndInvoke(re)); MessageBox.Show( "f" ); |
這個時候就會堵塞,等待StartMethod執行完才會走到第5句,沒有體現出異步的功能。
回調函數可以解決這個問題,可以將EndInvoke放在IAsyncCallback中執行,將3,4句改為
1 | IAsyncResult ir = id.BeginInvoke(AddComplete, null ); |
并添加以下函數:
1 2 3 4 5 | prvite void AddComplete(IAsyncResult result) { invokeDelegate handler = (invokeDelegate)((AsyncResult)result).AsyncDelegate; MessageBox.Show( handler.EndInvoke(result)); } |
這樣就函數便不用等待委托執行完,可以先執行第5句。
StartMethod方法如下:
1 2 3 4 5 | private void StartMethod() { Thread.Sleep(5000); MessageBox.Show( "c" ); } |
委托的BeginInvoke實際上是放在threadpool中的。
2.control的invoke和BeginInvoke都是在主線程上的所以它們都會阻塞主線程(control所在線程)。beginInvoke不會阻塞支線程,所以它只能作為支線程的異步
新聞熱點
疑難解答