title: Network threads blocking the GUI
body: <p>I'm just working on C # and WPF.</p>
  
  <p>I'm developing an application that should handle data transfers on the LAN.</p>
  
  <p>In particular, for each transfer progress bars are displayed, green if it is a download, red if it is an upload.</p>
  
  <p>Initially I had made some fictitious attempts in which I simulated transfers (the threads of the network were deactivated). So the bars were filled programmatically and I checked the performance of the GUI, everything was fine. In particular I could select the bars and make a context menu appear.</p>
  
  <p>After some time, we have developed the part of the network which basically does Read and Write TCP. For each chunk (or group of chunks) a Perform Step is made so that the bar advances.</p>
  
  <p>The number of chunks varies from file to file, but the number of steps to do is always 100 if there are more than 100 chunks, in this way 100 or less Perform Steps are always made for each transfer.</p>
  
  <p>The problem is that when the real transfers start, everything is slowed down, when I drag the window all around and the GUI is no longer responsive I can not even click on the bars to make the context menu appear. However, the progress of the bars works.</p>
  
  <p>We tried to disable the bars and make the transfers, the GUI is responsive and there are no problems.</p>
  
  <p>Probably we hurt the GUI refresh from the network.</p>
  
  <p>The Network has its own thread and the GUI another.</p>
  
  <p>What is the best way to refresh the bars by doing it from the Network?</p>
  
  <p>We currently use this, but we do not believe it is a good way, for sure it is not efficient.</p>
  
  <p>For example, we take the Network Client code:</p>
  
  <pre><code>...
  // Object representing a transfer (shared between GUI and Network)
  Transfer t = new Transfer(...);
  
  int bytesRead;
  var buffer = new byte[chunkSize];
  while ((bytesRead = file.Read(buffer, 0, buffer.Length)) &gt; 0)
  {
      if (t.Stop)
      {
          break;
      }
  
      nwStream.Write(buffer, 0, bytesRead);
      PBcount++;
      if (PBcount == PBchuks)
      {
          t.PerformStep(); // Make the progress bar to advance, works, but laggy
          PBcount = 0;
      }
  }
  ...
  </code></pre>
  
  <p>And the code relative to the PerformStep() is a public method of the Transfer shared object:</p>
  
  <pre><code>public void PerformStep()
  {
      CurrentStep = CurrentStep + 1;
      Application.Current.Dispatcher.Invoke(delegate { 
          MainWindow wnd = (MainWindow)Application.Current.MainWindow;
          wnd?.PerformStepProgressBarRefresh();
      });
  }
  </code></pre>
  
  <p>Following is the code of the MainWindow GUI method delegated to refresh the ListBox items:</p>
  
  <pre><code>public void PerformStepProgressBarRefresh()
  {
      Application.Current.Dispatcher.Invoke(delegate
      {
          TransfersXAML.Items.Refresh();
      });
  }
  </code></pre>
  
  <p>I do not know if it can be useful, but I'll put it anyway, it's the XAML code related to the progress bars:</p>
  
  <pre><code>&lt;ListBox x:Name="TransfersXAML"
           HorizontalContentAlignment="Stretch"
           ItemsSource="{Binding Transfers}"&gt;
      &lt;ListBox.ItemTemplate&gt;
          &lt;DataTemplate&gt;
              &lt;ProgressBar Height="30" Minimum="0"
                           Maximum="{Binding NSteps}"
                           Value="{Binding CurrentStep}"
                           Foreground="{Binding Color}" /&gt;
          &lt;/DataTemplate&gt;
      &lt;/ListBox.ItemTemplate&gt;
      &lt;ListBox.ContextMenu&gt;
          &lt;ContextMenu&gt;
              &lt;MenuItem Header="Get info" Click="GetTransferInfoClick" /&gt;
              &lt;MenuItem Header="Cancel" Click="CancelTransferClick" /&gt;
          &lt;/ContextMenu&gt;
      &lt;/ListBox.ContextMenu&gt;
  &lt;/ListBox&gt;
  </code></pre>
  
  <p>Do you know a better and more efficient system so that the threads of the Network can update progress bars in some way?</p>
  
  <p>After all, we do not know if we have done things correctly.</p>
  
  <hr>
  
  <p>We probably did not put all the information that could be useful to better understand the problem: signal it so that we can update the question.</p>
  
  <blockquote>
    <p>Update</p>
  </blockquote>
  
  <pre><code>public class Transfer
  {
      public enum Type_t
      {
          upload,
          download
      }
  
      public int NSteps { get; set; }
      public int CurrentStep { get; set; }
      public Type_t Type { get; set; }
      public string Color { get; set; }
      public string ID { get; set; }
      public string SenderID { get; set; }
      public string ReceiverID { get; set; }
  
      public Transfer(string senderID, string receiverID, Type_t _type, string _color)
      {
          SenderID = senderID;
          ReceiverID = receiverID;
          NSteps = 100;
          CurrentStep = 0;
          Type = _type;
          Color = _color;
          ID = Utils.GetHashString(senderID + receiverID + Utils.GetCurrentTimestamp());
      }
  
      public void PerformStep()
      {
          CurrentStep = CurrentStep + 1;
     Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =&gt;
          {
              MainWindow wnd = (MainWindow)Application.Current.MainWindow;
              wnd?.PerformStepProgressBarRefresh();
          }));
      }
  }
  </code></pre>