A very obscure question, I will assume:
- You are running the Windows Winforms application, not the ASP.Net web page.
- You want to run a background calculation, which can take a lot of time, and you don't want your user interface to be locked when this happens.
- You want your user interface to get some sort of result when doing background calculation.
- You want your background calculation to complete when it provides your user interface with the result.
If so, you should use an asynchronous delegate, not a thread. For instance:
string SleepAndReturnParam(string param1) { System.Threading.Thread.Sleep(10000); return param1; } // Declare a delegate matching our async method. public delegate string DelegateWithParamReturningString(string param1); private void button1_Click(object sender, EventArgs e) { var myDelegate = new DelegateWithParamReturningString(SleepAndReturnParam); // Run delegate in thread pool. myDelegate.BeginInvoke("param1", OnCallBack, // Completion callback this); // value to pass to callback as AsyncState } private void OnCallBack(IAsyncResult ar) { // first cast IAsyncResult to an AsyncResult object var result = ar as System.Runtime.Remoting.Messaging.AsyncResult; // grab the delegate var myDelegate = result.AsyncDelegate as DelegateWithParamReturningString; // Exit delegate and retrieve return value. string returnValue = myDelegate.EndInvoke(ar); // Declare an anonymous method to avoid having to define // a method just to update a field. MethodInvoker formFieldUpdater = delegate { formTextField.Text = returnValue; }; // Winforms controls must be modified on the thread // they were created in. if (formTextField.InvokeRequired) Invoke(formFieldUpdater); else formFieldUpdater(); }
source share