How to Kill or Start a New Background Process in C#/Csharp

The following snippet allows you to check if a process is already running in the background. If the process is already running it will prompt the user to whether start a new process or continue with the existing one that is running.

        private void checkForDataInProgress()
        {
            if (!this.bConnectedToDatabase)
                return;

            Process proc = new Process();
            string sNumThreads = Properties.Settings.Default.NumberOfLocalThreads.ToString();
            string sProcArgs = "\"" + this.sSQLConnectString + "\" \"" + Properties.Settings.Default.XMLSaveDir + "\" \"" + Properties.Settings.Default.DLLDir + "\" " + sNumThreads;
            proc.StartInfo = new ProcessStartInfo(Properties.Settings.Default.DataImporterAppLocation, sProcArgs);
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.SynchronizingObject = this;
            Process[] procs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(proc.StartInfo.FileName));

            foreach (Process p in procs)
            {
                if (p.MainModule.FileName == proc.StartInfo.FileName)
                {

                    if (MessageBox.Show(this, "Data is currently being imported.\n\rIf you want to stop this import and begin a new import, click \"YES\"\n\r" +

                        "To allow the current data import to continue, click \"NO\"", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        proc.Exited += new EventHandler(proc_Exited);
                        proc.EnableRaisingEvents = true;
                        proc.Start();
                        this.tsDataCollectionLabel.Visible = true;
                        this.tsDataCollectionPGB.Visible = true;
                    }

                    return;
                }
            }
            proc.Exited += new EventHandler(proc_Exited);
            proc.EnableRaisingEvents = true;
            proc.Start();
            this.tsDataCollectionLabel.Visible = true;
            this.tsDataCollectionPGB.Visible = true;
        }

        void proc_Exited(object sender, EventArgs e)
        {
            this.tsDataCollectionLabel.Visible = false;
            this.tsDataCollectionPGB.Visible = false;
            checkForDataInProgress();
        }

Comments

Popular posts from this blog

How to Create a Configuration.INI Files in VB6

How to Make Windows Form Transparent using Visual Basic 6/VB6

How to Set Windows Form Always on Top of Other Applications in VB6