开发者

How to send my program to background while a certain process is running

I have a program that starts another program (iexplore.exe), then my program should go "invisible" or atlast to background, and stay there while this asd.exe is running. This code is working, BUT it eats memory, and sometimes its just stays hiden while asd.exe is not running anymore. There must be a more efficient way to do this =) So my program code :

   this.Hide();
   Process.Start(Path.Combine(Path, "iexplore.exe")); 
   Process[] Running_ = null;
   do
   { // this loops eats memory!
      System.Threading.Thread.Sleep(500);
      Running_ = null;
      R开发者_StackOverflow社区unning_ = Process.GetProcessesByName("iexplore");
   }while (Running_.Length > 0);
   this.Show();


You'll want to use the Process.Exited event here, prevents blocking the UI thread and avoids hassling threads. Like this:

    private void button1_Click(object sender, EventArgs e) {
        var prc = new Process();
        prc.EnableRaisingEvents = true;
        prc.Exited += processExited;
        prc.StartInfo = new ProcessStartInfo("notepad.exe");
        prc.Start();
        this.Hide();
    }

    private void processExited(object sender, EventArgs e) {
        this.BeginInvoke(new Action(() => {
            this.Show();
            this.BringToFront();
        }));
    }


What about the Process.WaitForExit method?

this.Hide();
Process p = Process.Start(Path.Combine(WoWPath, "asd.exe"));
p.WaitForExit();
this.Show();


I like what MatthiasG has done, but WaitForExit() is a blocking call...Your program will be hidden until asd.exe finishes executing, but your program will not be doing anything productive.

This may be the desired result. If not, I would

  1. Hide the form -> this.Hide();
  2. Create a thread (BackgroundWorker will suffice)... In the DoWork() event, create the Process object for asd (as MatthiasG had done):

    Process p = Process.Start(Path.Combine(WoWPath, "asd.exe"));
    p.WaitForExit();
    
  3. In the RunWorkerCompleted event, have this.Show();


  • No need to null WoWRunning_. Process.GetProcessesByName changes the reference anyways
  • Call .Dispose() !


You need to call Dispose() on each object in your array, then it stops to eat memory.

I mean instead of WoWRunning_ = null; put there something like foreach(Process p in WoWRunning_) p.Dispose();

But anyway your algorithm should be revised completely, it is quite expensive because you load an array of all processes again and again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜