troubleshooting Question

Real Time Programs, Databases and Threads.

Avatar of AlHal2
AlHal2Flag for United Kingdom of Great Britain and Northern Ireland asked on
ProgrammingDatabases
7 Comments2 Solutions131 ViewsLast Modified:
I'm trying to understand real time programming and found this sample program online.
Why the need for threading?
Assuming there is a genuine need for threading, what about a separate task rather than a separate thread?
What's the advantage of doing it this way rather than using a timer.
What's the best way to update a csv file with the contents of a Database table as near to real time as possible?


using System;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace Project1
{
    public partial class Form1 : Form
    {
        private Thread cpuThread;
        private double[] cpuArray = new double[30];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void getPerformanceCounter()
        {
            //override 3 of 6
            var cpuPerfCounter = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            while (true)
            {
                cpuArray[cpuArray.Length - 1] = Math.Round(cpuPerfCounter.NextValue(), 0);
                Array.Copy(cpuArray, 1, cpuArray,0, cpuArray.Length - 1);
                if (cpuChart.IsHandleCreated)
                {
                    this.Invoke((MethodInvoker)delegate { UpdateCpuChart(); }); 
                }
                else
                {

                }
                Thread.Sleep(1000);
            }
        }
        private void UpdateCpuChart()
        {
            cpuChart.Series["Series1"].Points.Clear();
            for (int i=0;i<cpuArray.Length-1;i++)
            {
                cpuChart.Series["Series1"].Points.Add(cpuArray[i]);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cpuThread = new Thread(new ThreadStart(this.getPerformanceCounter));
            cpuThread.IsBackground = true;
            cpuThread.Start();
        }
    }
}
SOLUTION
nociSoftware Engineer
Join our community to see this answer!
Unlock 2 Answers and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros