-1

I'm getting the error "an object reference is required for the non-static field, method, or property 'process.waitforexit()"

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace cpu_benchmark
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process.Start("C:\\Users\\Reghunaath A A\\source\\repos\\cpu benchmark\\resources\\benchmark result\\bench.exe");
            Process.WaitForExit(100000);
            //StreamReader sr1 = new StreamReader("C:\\Users\\Reghunaath A A\\source\\repos\\cpu benchmark\\resources\\benchmark result\\count.txt");
            textBox1.Text = "hi";

        }
    }
}

.

Reghunaath
  • 101
  • 1
  • 2
  • 8
  • 1
    Possible duplicate of [How do I start a process from C#?](https://stackoverflow.com/questions/181719/how-do-i-start-a-process-from-c) – OneCricketeer Oct 27 '19 at 19:18
  • Any time a method doesn't do what you think it should, the first thing you should do is [read the documentyation](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.exitcode). – Dour High Arch Oct 27 '19 at 19:21

2 Answers2

1

Unlike Start, which is a static method, WaitForExit is an instance method.

The Start method returns an instance of the Process class, and it's that instance you need to wait for its exit - so your code should look like this:

var process = Process.Start("C:\\Users\\Reghunaath A A\\source\\repos\\cpu benchmark\\resources\\benchmark result\\bench.exe");
process.WaitForExit(100000);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

An instance method needs to be accessed from the instance of an object. Assume you instantiate an object of type O1 like this:

O1 myObject = new O1();

Then an instance method is called like myObject.InstanceMethod(). On the contrary, a static method doesn't need an object instance, it's like this O1.StaticMethod().

In your particular case, Start is a static method and WaitForExit is an instance method. The Start method returns an object instance of the Process class, and it's that instance you use to call WaitForExit, the code would look like this:

var process = Process.Start("C:\\Users\\Reghunaath A A\\source\\repos\\cpu benchmark\\resources\\benchmark result\\bench.exe");
process.WaitForExit(100000);
Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21