1

I have a form application in C# which does what it needs to however all on the UI thread. Its is not computationally expensive but fairly time consuming as it waits for responses from other systems and locks up the UI during this.

Below is a snippet from my routine.

private void btnRun_Click(object sender, EventArgs e)
    {

        TextAppend("Checking Laser Marker TCP/IP...");

        foreach(string t in Steps)
        {
            var itm = new ListViewItem(t);
            listView1.Items.Add(itm);
        }
        listView1.Items[0].BackColor = Color.PaleGoldenrod;
        progressBar1.Value = 0;
        LabelShows(1);

        //Check the TCP/IP connection
        progressBar1.Value = 21;

        bool checkIP = RunModule.CheckConnection("GI SN", IP, port, this);

        if (checkIP == false)
        {
            listView1.Items[0].BackColor = Color.Red;
            MessageOK("Failed to connect to the Laser Marker! Please check IP, Port and serial numbers match the Laser marker.", "warn");

            LabelShows(0);
            return;
        }
     }

The section:

bool checkIP = RunModule.CheckConnection("GI SN", IP, port, this);

    if (checkIP == false)
    {
        listView1.Items[0].BackColor = Color.Red;
        MessageOK("Failed to connect to the Laser Marker! Please check IP, Port and serial numbers match the Laser marker.", "warn");

        LabelShows(0);
        return;
    }

Occurs in a similar fashion several time further down the routine with different functions. All functions run from a different class.

I have looked at using backgroundworkers but these report progress rather than a bool. I have looked at Task.Run() but I cannot see a way to implement it. Can anyone provide advice on how to better structure my routine?

MJ2507
  • 113
  • 1
  • 12
  • 2
    Possible duplicate of [How to make BackgroundWorker return an object](https://stackoverflow.com/questions/939635/how-to-make-backgroundworker-return-an-object) – Sani Huttunen Mar 23 '18 at 17:15

1 Answers1

1

You can use BackgroundWorker to achieve what you want.
The key is DoWorkEventArgs which has the property Result which is passed on to the RunWorkerCompleted event. (The RunWorkerCompleted event runs in the UI thread):

private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
  ...
  e.Result = RunModule.CheckConnection("GI SN", IP, port, this);
}

private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  var checkIP = (bool) e.Result;

  if (checkIP == false)
  {
    listView1.Items[0].BackColor = Color.Red;
    MessageOK("Failed to connect to the Laser Marker! Please check IP, Port and serial numbers match the Laser marker.", "warn");

    LabelShows(0);
  }
}
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
  • Thanks for the response! Can I tell my primary UI thread to wait for the `e.result` to be returned before continuing? the main thread requires the tasks to happen in sequence. – MJ2507 Mar 23 '18 at 18:46