User interface freezes in heavy computing

I load huge files into memory, but with this calculation my application freezes.

Any idea what the problem is with my code?

public void Drop(DragEventArgs args) { BackgroundWorker worker = new BackgroundWorker(); string fileName = IsSingleTextFile(args); if (fileName == null) return; worker.DoWork += (o, ea) => { try { StreamReader fileToLoad = new StreamReader(fileName); string filecontent = fileToLoad.ReadToEnd(); fileToLoad.Close(); // providing the information to the UI thread Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => SfmLogFile = filecontent)); } catch (Exception) { throw; } }; worker.RunWorkerCompleted += (o, ea) => { args.Handled = true; IsBusy = false; }; // Mark the event as handled, so TextBox native Drop handler is not called. IsBusy = true; worker.RunWorkerAsync(); } 
+4
source share
2 answers

I would convert your example to the following:

 public void Drop(DragEventArgs args) { string fileName = IsSingleTextFile(args); if (fileName == null) return; // It is better to create worker after check for file name. BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (o, ea) => { try { string filecontent = ReadAllText(fileName); ea.Result = fileContent; } catch (Exception) { throw; } }; worker.RunWorkerCompleted += (o, ea) => { var fileContent = ea.Result as string; Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => SfmLogFile = filecontent)); // if IsBusy propery is not on the UI thread, then you may leave it here // otherwise it should be set using the dispatcher too. IsBusy = false; }; IsBusy = true; worker.RunWorkerAsync(); // Mark the event as handled, so TextBox native Drop handler is not called. args.Handled = true; } 
+2
source

I'm not sure if this is the cause of your problem, but you set args.Handled in the callback for the desktop, so it will be called after the forwarding event handler returns. It will not have the desired effect, since it is too late, and this can ruin something in event handling.

+1
source

Source: https://habr.com/ru/post/1384553/


All Articles