running a thread in parallel

105 views Asked by At

I am inside a threat updating a graph and I go into a routine that makes a measurement for 4 seconds. The routine returns a double. What I am noticing is that my graph stops showing activity for 4 seconds until I am done collecting data. I need to start a new thread and put the GetTXPower() activity in the background. So in other words I want GetTXPower() and the graph charting to run in parallel. Any suggestions?

here is my code:

             stopwatch.Start();
            // Get Tx Power reading and save the Data
            _specAn_y = GetTXPower();
            _pa_Value = paData.Start;
            DataPoint.Measurement = _specAn_y;
            //Thread.Sleep(50);
            double remaining = 0;                
            do
            {
              charting.stuff  
            }
            uxChart.Update();
2

There are 2 answers

1
Jaanus Varus On BEST ANSWER

I suggest looking into Task Parallel Library.

Starting with the .NET Framework 4, the TPL is the preferred way to write multithreaded and parallel code.

Since you also need the result back from GetTXPower, I would use a Task<double> for it.

Task<double> task = Task.Factory.StartNew<double>(GetTXPower);

Depending on when you need the result, you can query if the task has completed by checking task.IsCompleted or alternatively block the thread and wait for the task to finish by calling task.Wait(). You can fetch the result through task.Result property.

An alternative would be to add a continuation to the initial task:

Task.Factory.StartNew<double>(GetTXPower).ContinueWith(task => 
{
    // Do something with the task result.
});
4
Patrick vD On

Make a void method (I'll call it MeasureMentMethod) that collects the data. The create a Thread using the following code:

Thread MeasurementThread = new Thread(new ThreadStart(MeasurementMethod));

You can then run the thread with

MeasurementThread.Start();

And if your Thread has something like this:

while(true){
    //Run your code here
    Thread.Sleep(100);
}

Then you can just start it at the beginning, and it will just keep collecting data.

So, you would have your main thread that would update the chart, and you would start the thread that would get the data on the side.