1

I'm trying to run a function after a thread has completed running. My thread starts when an UI button is pressed and the thread takes a while to complete.
Once it's done running I want to call a function. Here is the code I tried so far. When I try to run my code the thread never executes and the application freezes. Any suggestion on how to fix this would be helpful.

public bool StartProbe()
{
    if (File.Exists(Path.Combine(ObsProbeFolder, "probePJM.exe")))
    {
        ThreadStart ProbeThreadStart = new ThreadStart(() =>
        // right side of lambda    
            {
               // does stuff
            });

            ProbeThread = new Thread(ProbeThreadStart);
            ProbeThread.Priority = ThreadPriority.BelowNormal;
            ProbeThread.SetApartmentState(ApartmentState.STA);
            ProbeThread.Start();

    }
    else
    {                      
        return false;
    }

    // waiting for thread to finish 
    ProbeThread.Join();
    // run a function
    loadData();

    return true;
} 
VMAtm
  • 27,943
  • 17
  • 79
  • 125
Satish
  • 325
  • 1
  • 3
  • 12

1 Answers1

0

I would use a BackgroundWorker:

Worker = new BackgroundWorker();
            Worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
            Worker.DoWork += Worker_DoWork;

            Worker.RunWorkerAsync(new BackgroundArguments()
            {
                // arguments
            });

Work on alternate thread:

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{       
    // do stuff
}

Return to UI thread:

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
       // load data or whatever on UI thread
    }
mjhouseman
  • 164
  • 2
  • 18
  • Why use such an old structure as BackgroundWorker, if you can use TPL and/or await? – VMAtm Feb 10 '17 at 19:17
  • There is nothing wrong with using BackgroundWorker, especially for a single process such as the user described. I agree that TPL is better for running multiple processes, but for a single process they are virtually interchangeable. – mjhouseman Feb 13 '17 at 20:30