Is there a way to simplify the code for handling multiple cross-threaded exceptions?

36 views Asked by At

I'm making a 1:N asynchronous chat program in C# Windows Form.

When the server connection was successful, an attempt was made to change the Enabled property of the Connect button to false.

A cross-thread exception was thrown at this time.

Fortunately I know how to deal with cross-threaded exceptions using Invoke.

So I wrote the code as below.

private void ConnectEnabledChange(bool state)
{
  this.Invoke(new Action(delegate ()
  {
    Connect.Enabled = state;
  }));
}

The problem, however, is that we need to change the properties of the Connect button as well as the properties of several other controls.

try 
{
  server.Start();
  ConnectEnabledChange(false);
  DisConnectEnabledChange(true);
  StateLabelChange("Current State : Connected");
}

...

private void ConnectEnabledChange(bool state)
{
  this.Invoke(new Action(delegate ()
  {
    Connect.Enabled = state;
  }));
}

private void DisConnectEnabledChange(bool state)
{
  this.Invoke(new Action(delegate ()
  {
    DisConnect.Enabled = state;
  }));
}

private void StateLabelChange(string state)
{
  this.Invoke(new Action(delegate ()
  {
    StateLabel.Text = state;
  }));
}

I think Then it seems inefficient to write code like the above every time a cross-thread exception occurs.

Is there any way to integrate them into one?

Or can you make the code simpler?

Thank you for your help.

0

There are 0 answers