I am trying to make my C # application multithreaded because sometimes I get an exception that says I made a call to the thread in an unsafe way. I have never done multithreading before in a program, so bear with me if I seem a little ignorant about this problem.
An overview of my program is that I want to make a performance monitoring application. This implies using the performance and performance class in C # to start and monitor application processor time and send that number back to the user interface. However, in a method that actually calls the nextValue method of the performance counter (which is set to execute every second thanks to a timer), sometimes I get the above exception, which would say that the thread was called in an unsafe way.
I have attached the code for your reading. I know this is a rather time-consuming issue, so I would be very grateful if someone could help me on where to create a new thread and how to safely call it. I tried to take a look at what was on MSDN, but it just bothered me.
private void runBtn_Click(object sender, EventArgs e) { // this is called when the user tells the program to launch the desired program and // monitor it CPU usage. // sets up the process and performance counter m.runAndMonitorApplication(); // Create a new timer that runs every second, and gets CPU readings. crntTimer = new System.Timers.Timer(); crntTimer.Interval = 1000; crntTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); crntTimer.Enabled = true; } private void OnTimedEvent(object source, ElapsedEventArgs e) { // get the current processor time reading float cpuReading = m.getCPUValue(); // update the current cpu label crntreadingslbl.Text = cpuReading.ToString(); // } // runs the application public void runAndMonitorApplication() { p = new Process(); p.StartInfo.UseShellExecute = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = fileName; p.Start(); pc = new System.Diagnostics.PerformanceCounter("Process", "% Processor Time", p.ProcessName, true); } // This returns the current percentage of CPU utilization for the process public float getCPUValue() { float usage = pc.NextValue(); return usage; }
multithreading c # process winforms performancecounter
Waffles
source share