Dispatcher.Invoke assigns a delegate to execute on the user interface thread. You do not want to execute any potentially long-term code in the user interface thread, as this is what your application freezes.
If you want to call Directory.EnumerateFiles in the background thread, you can run the task:
Task.Factory.StartNew(()=> { //get the files on a background thread... return Directory.EnumerateFiles(DirName, Ext, SearchOption.TopDirectoryOnly); }).ContinueWith(task => { //this code runs back on the UI thread IEnumerable<string> theFiles = task.Result; //... }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
Please note that you cannot access any user interface control in the background thread, although you should only do lengthy work on the background thread, and then you can use the ContinueWith method if you want something with the results to return the user interface thread. for example, to set the ItemsSource property of an ItemsControl element or to set the Visibility property of a ProgressBar to Collapsed or something like that.
source share