CS.BANNED.INVOKE

Prefer asynchronous calls to synchronized calls.

Avoid using Windows.Forms.Control.Invoke synchronous method. Consider using the Windows.Forms.Control.BeginInvoke asynchronous method, especially if you dont need the return value. The Invoke synchronous method could potentially lead to deadlocks which are very difficult to trace.Windows.Forms.Control methods can be used only in the GUI thread that created the control except for cross-threading Invoke/BeginInvoke methods.

Another thread using the synchronous Invoke method can potentially cause a deadlock if it locks a resource that is synchronized in the GUI thread.

This situation can be avoided with an asynchronous BeginInvoke call.

Mitigation and prevention

Enforce reviews of code with potential deadlock situations.

Vulnerable code example

Copy
  public class Class1
  {
      private TextBox _TextBox;
      private void Update(string text)
      {
          _TextBox.Text = text;
      }
      public delegate void UpdateDelegate(string text);
      void method1()
     {
         _TextBox.Invoke(new UpdateDelegate(this.Update), new string []{"info"}); // VIOLATION
     }
 }

Fixed code example

Copy
  public class Class1
  {
      private TextBox _TextBox;
      private void Update(string text)
      {
          _TextBox.Text = text;
      }
      public delegate void UpdateDelegate(string text);
      void method1()
     {
         _TextBox.BeginInvoke(new UpdateDelegate(this.Update)); // FIXED
     }
 }