So I am playing around with one of my projects and what is causing an issue right now is when I click my Start
button this method runs.
public void Start()
{
if (!ServerIsRunning)
{
ConsoleOutput.Clear();
pServer = new Process();
pServer.StartInfo.FileName = "java";
pServer.StartInfo.Arguments = @"-jar " + "-Xms512M -Xmx1G myJavaFile.jar";
pServer.Start();
PID = pServer.Id;
counter = new PerformanceCounter("Process", "% Processor Time", pServer.ProcessName, true);
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
}
}
I have created a global null property for the PerformanceCounter
like so
private PerformanceCounter counter;
And as you can see in the start method that's where we are assigning it a value.
I created this tick event aswell for my timer that updates a property
void timer_Tick(object sender, EventArgs e)
{
FindServerProcess();
double pct = counter.NextValue() / 10;
ServerCPU = pct.ToString("0.0");
}
And here is the method inside that finds the process corresponding to a certain PID
public void FindServerProcess()
{
Process[] processes = Process.GetProcesses();
foreach (var process in processes)
{
if (process.Id == PID)
{
Console.WriteLine("Found the process!");
}
}
}
When I click start it let's me know in the Output window that it finds the process as expected by printing out the message Found the process!
.
However.. This is where it gets weird. If I click my stop button
private void Stop(string StopCommand)
{
counter.Close();
counter = null;
timer.Stop();
pServer.StandardInput.WriteLineAsync(StopCommand);
}
it closes the counter, makes it null and I stop the timer that calls the tick event. Then I am also issuing a command which is just stop
to the console stream which simply closes the process. At this point the process has been closed, I cant see it in the Task manager anymore. When I click start however, it starts prining out Found the process!
two times at the time so parallel, and the property value it's changing seems to be double. Why is that? Am I not closing the property safely? Or did I forget to dispose of some objects?
I think your problem with two lines of Found the process!
is caused by your Start()
function, specifically the line:
timer.Tick += timer_Tick;
As you described your actions of pressing, Start, Stop, and then Start again. The timer.Tick
event is being added twice (once each time the Start()
function is run.
To counter it, simply add the line
timer.Tick -= timer_Tick;
beforehand.
Whenever you add an Event Handler at run time, you should always precede the call with the -=
syntax to remove the previously assigned Event Handler (unless you really want it to run more than once)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.