试试这个。
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