試試這個。
class Form1: Form
{
public void ButtonWasClicked(object sender, EventArgs e)
{
/* Call the UI's Invoke() method */
this.Invoke((MethodInvoker)delegate()
{
/* Stuff to do.. you can access UI elements too without
* the nasty "Control accessed from another thread.."
* Use BeginInvoke() only if you have code after this section
* that you want the UI to execute without waiting for this
* inner blockto finish.
*/
});
}
}
關於BeginInvoke的(),它是用來使函數將立即返回並無需等待完成該方法的下一行就會被執行等,等等。
不同之處在於,如果您創建了一個線程,就可以像對待其他線程一樣對它進行更多的控制。您將遇到CrossThreadExceptions!而如果您使用IAsyncResult和BeginInvoke(),則您將無法控制異步操作的執行流程,因爲它由運行時管理。
通過調用,您還可以向方法發送更多參數並在操作完成後調用方法。
MyDelegateWithTwoParam del = new MyDelegateWithTwoParam(_method);
AsyncCallback callback = new AsyncCallback(_callbackMethod);
IAsyncResult res = del.BeginInvoke(param1, param2, callback, null);
private void _callbackMethod(IAsyncResult iar) {
/* In this method you can collect data that your operation might have returned.
* If MyDelegateWithTwoParam has a return type, you can find out here what i was. */
}
我已經廣泛用於UI開發。我會更多地使用線程來處理類似服務的對象。 (想象一個停留並監聽TCP連接的對象)以及用於UI後臺工作的異步方法(也可以看看BackgroundWorker)。 如果第一種方法需要額外的一秒才能開始,請不要擔心:Thread.Abort()不是 始終是您的最佳解決方案。試試你的程序代碼中的_abort標誌並鎖定它。
希望我已經回答了這個問題。
利奧Bruzzaniti
有關信息,請明確說明您是否指Control.BeginInvoke和Delegate.BeginInvoke;我相信你的意思是第一個,但他們幾乎是完全相反的,所以區別很重要。 – 2009-08-04 09:34:32
它是第一種方法(Control.BeginInvoke),因爲我在表單上執行此操作。 – 2009-08-04 09:42:27