Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello! I have a application that is opening EXE's and the closes them after a certain ammount of time and the issue is quite simple.. It wont close the applications it opens, I tried Process.Kill(); and TheNameOfTheVariable.Close();

But it wont close, if I do Process.Kill(); It gives me a error saying
Cannot process request because the process has exited.


and if i do
TheNameOfTheVariable.Close(); it just loads and restarts the timer.

Any solutions?

C#
private void timer1_Tick(object sender, EventArgs e)
{
    var firstProcess = Process.Start(textBoxFirst.Text);
    int timeOne = Convert.ToInt32(MinTextBoxFirst.Text);
    Thread.Sleep(timeOne);
   // firstProcess.Kill();
   // if (!firstProcess.HasExited) firstProcess.Kill();
   // firstProcess.Kill();
   // MessageBox.Show("The Process Has Been Killed!");
    firstProcess.Close();



}



I've commented out other methods I've tried using.



CHANGES



C#
I changed up the code, removed the timer and used this code

        private void startlbl_Click(object sender, EventArgs e)
        {
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);

            var firstProcess = Process.Start(textBoxFirst.Text);
            int timeOne = Convert.ToInt32(MinTextBoxFirst.Text);
            Thread.Sleep(timeOne);
            firstProcess.Kill();
        }

and it gives me this error

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

Additional information: Cannot process request because the process has exited.



CHANGES v2.0

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

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

        

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        private void label1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void BrowseFirst_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string FilePath = ofd.FileName;
                textBoxFirst.Text = FilePath;
            }
        }

        private void BrowseSecond_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd1 = new OpenFileDialog();
            if (ofd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string FilePath = ofd1.FileName;
                textBoxSecond.Text = FilePath;
            }
        }

        private void BrowseThird_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd2 = new OpenFileDialog();
            if (ofd2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string FilePath = ofd2.FileName;
                textBoxThird.Text = FilePath;
            }
        }

        private void startlbl_Click(object sender, EventArgs e)
        {
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);
            Process.Start(textBoxFirst.Text);

            var firstProcess = Process.Start(textBoxFirst.Text);
            int timeOne = Convert.ToInt32(MinTextBoxFirst.Text);
            Thread.Sleep(timeOne);
             firstProcess.Kill();
            // if (!firstProcess.HasExited) firstProcess.Kill();
            // firstProcess.Kill();
            // MessageBox.Show("The Process Has Been Killed!");
            //firstProcess.Close();
        }
}
    }
}



Added my source code ^

What I have tried:

I commented out the methods I've tried using.
Posted
Updated 15-Jun-16 7:52am
v3
Comments
Sergey Alexandrovich Kryukov 15-Jun-16 12:43pm    
Why do you sleep in the timer tick event handler? Why do you use the timer at all? Do you have other threads?
—SA
BladeLogan 15-Jun-16 12:45pm    
I will have other threads and if I would code the whole timer process it would be alot more code, im just trying to do it as profficient as possible.
Sergey Alexandrovich Kryukov 15-Jun-16 13:10pm    
It's not clear if you are using any additional threads now, but please see my Solution 2.
Why Thread.Sleep, why?
—SA
BladeLogan 15-Jun-16 12:52pm    
I changed up the code, removed the timer and used this code

private void startlbl_Click(object sender, EventArgs e)
{
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);

var firstProcess = Process.Start(textBoxFirst.Text);
int timeOne = Convert.ToInt32(MinTextBoxFirst.Text);
Thread.Sleep(timeOne);
firstProcess.Kill();
}

and it gives me this error

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

Additional information: Cannot process request because the process has exited.
Sergey Alexandrovich Kryukov 15-Jun-16 13:09pm    
You have to provide comprehensive exception information. Don't forget InnerException.
—SA

BladeLogan wrote:

I will have other threads and if I would code the whole timer process it would be a lot more code, I'm just trying to do it as profficient as possible.
You did not answer about the timer use (this is not a separate process, but the thread can be separate).
To allow your current process to terminate itself, you have to terminate each of your other threads. It can be done in different ways; you can let threads exit by themselves, using some logic and inter-thread communications, or Abort them (aborting needs care and clear understanding of what you are doing; this is not a trivial thing).

(By the way, one type of timers, System.Windows.Forms.Timer always calls event handlers in the current UI thread and is the easiest to use, in this respect, but if you need any behavior which is supposed to look like more or less periodic, this type is totally unsuitable, due to its prohibitively low timing accuracy. It can be used for implementing some kinds of timeouts, in cases where accuracy is not critical at all.)
Alternatively, you can make all additional thread background threads, then the runtime will terminate them, but, in most cases, I don't advise it, because then you cannot make termination of such thread controllable. In certain situations, using background thread is acceptable though; please see: Thread.IsBackground Property (System.Threading).

I would be very careful with timers. In so many questions related to timers asked on CodeProject, I could see very few cases when using timers was reasonable, in absolute majority of cases, the use of them was misconception. This is the point which could give you the most of trouble.

—SA
 
Share this answer
 
v3
When I try you code with "hardcoded" variables:
C#
var firstProcess = Process.Start(@"D:\Documents\AA Backed Up\My Projects\UtilityApplications\BulkFileRename\bin\Release\BulkFileRename.exe");
int timeOne = 5000;
Thread.Sleep(timeOne);
firstProcess.Kill();

The app opens, waits a few seconds, and closes again. I get no error.
I suspect it's the Timer that's causing it - check the interval on the timer, and make sure it is longer than the amount of time you Sleep your thread for, or disable the timer while the operation is going on. It's possible that it just appears not to be closing because the timer means you keep opening it again.
I'd be very reluctant to use Thread.Sleep in a timer Tick event handler anyway - you might get a better result using the timer to decide if you need to open the app, wait a while, or close it instead of Sleeping inside it. And do remember that the Sleep parameter is in milliseconds - so if you are entering small values, the app may not be fully running before you try to kill it.
 
Share this answer
 
Comments
BladeLogan 15-Jun-16 12:53pm    
I changed up the code, removed the timer and used this code

private void startlbl_Click(object sender, EventArgs e)
{
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);
Process.Start(textBoxFirst.Text);

var firstProcess = Process.Start(textBoxFirst.Text);
int timeOne = Convert.ToInt32(MinTextBoxFirst.Text);
Thread.Sleep(timeOne);
firstProcess.Kill();
}

and it gives me this error

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

Additional information: Cannot process request because the process has exited.
OriginalGriff 15-Jun-16 13:47pm    
Try it with exactly the code I provided - hardcode the path to a "known" exe file that doesn't do anything so it doesn't corrupt any data when it gets killed.
See what happens then.
BladeLogan 15-Jun-16 13:50pm    
I did but I dont want to hardcode my application everytime I need to open a different EXE, thats why I have the browse button and the openfile dialog
OriginalGriff 15-Jun-16 13:59pm    
I understand that - but the first thing to do is to try and isolate exactly where the problem is. So reduce the variables: known working EXE, known Sleep period, known working code (on my machine at least).
If that works, we can try introducing the variables back until something fails - and then we have a better idea where the problem is.
BladeLogan 15-Jun-16 14:08pm    
Okay so I tried your exact code and it still gives me this error.
https://i.gyazo.com/4723a029fc4fd2959ddb3685d7181ec7.png

System.InvalidOperationException was unhandled
HResult=-2146233079
Message=Cannot process request because the process has exited.
Source=System
StackTrace:
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.Kill()
at Software_Restarter.Form1.startlbl_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Label.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Software_Restarter.Program.Main()
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900