GuillaumeA
GuillaumeA

Reputation: 3545

C# WPF GUI performance MVVM

I'm looking for a way to improve performances of my code. I've got a WPF GUI with a TextBox and a graph (from OxyPlot package). I used StopWatch to find the place where the code is less efficient and I found that it takes more time to update the Text of my TextBox than to fill the string. For example, if the property MyText is bound to the Text property of the TextBox then this part of code

Application.Current.Dispatcher.Invoke(()=>{
   MyText = currentString;
});

takes more time than all of this

StringBuilder sb = new StringBuilder();
RetrieveDataFromDevice();
FillString(sb);
string currentString = sb.ToString();

And with the StopWatch :

Task.Factory.StartNew(() =>
{
   var sw = new StopWatch();
   sw.Start();
   StringBuilder sb = new StringBuilder();
   RetrieveDataFromDevice();
   FillString(sb);
   string currentString = sb.ToString();
   Trace.WriteLine(sw.ElapsedMilliseconds.ToString()); //5ms
   sw.Restart();
   Application.Current.Dispatcher.Invoke(()=>{
      MyText = currentString;
   });
   Trace.WriteLine(sw.ElapsedMilliseconds.ToString()); //10ms
}

There is a performance issue as I can not refresh the string (or the graph) more often than every 15ms. Are there any way to improve these performances ?

Upvotes: 3

Views: 885

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27871

Try to use the Dispatcher.BeginInvoke method instead of the Invoke method.

This method does not wait for the UI thread to process the request before being able to continue. It simply puts the request in the UI thread's queue and then returns immediately.

This will allow you to do more processing in the background thread while the UI thread is processing UI requests.

Having said that, there should be a reasonable amount of UI update requests that you ask the UI thread to process per second.

Upvotes: 4

Related Questions