You are returning a long operation to the user interface thread. Let me comment on your example:
Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { // here we are in the background thread Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { // here we are back in the UI thread Thread.Sleep(15000); })); } ));
So you should change your example as follows:
Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() {
As already mentioned, it is easier to use the BackgroundWorker class. Here is an example:
private void DoSomeAsyncWork() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (sender, args) => { // do your lengthy stuff here -- this will happen in a separate thread Thread.Sleep(15000); } bw.RunWorkerCompleted += (sender, args) => { if (args.Error != null) // if an exception occurred during DoWork, MessageBox.Show(args.Error.ToString()); // do your error handling here // do any UI stuff after the long operation here ... } bw.RunWorkerAsync(); // start the background worker }
Heinzi
source share