Try this.
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.
*/
}
}
}
Regarding BeginInvoke(), it is used so the function will return immediately and the next line will be executed and so on and so forth without waiting for the method to finish.
The difference is that if you create a thread you will have more control over it just like any other thread. You will run into CrossThreadExceptions! Whereas if you use IAsyncResult and BeginInvoke(), you will not have control over the execution flow of the asynchronous operation as it's managed by the runtime.
With invocation you can also send more parameters to a method and have a method being called once the operation is finished.
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. */
}
I've widely used both for UI development. I would use threads more for service-like objects. (Think of an object that stays and listens for TCP connections) and asynchronous methods for background work behind a UI (have a look at BackgroundWorker too).
Don't worry if the first approach took an extra second to start: Thread.Abort() is not
always your best solution either. Try _abort flags in your process code and lock it.
Hope I've answered the question.
Leo Bruzzaniti