0

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Timers;
using System.Diagnostics;

using System.Threading;

namespace ConsoleApplication2 {
    class Program {

        public static System.Timers.Timer aTimer;
        public static System.Diagnostics.Stopwatch sw;
        public static Boolean HasNotepadclosed;
        public static Process pr;

        static void Main(string[] args) {

            Boolean HasNotepadclosed = false;
            sw = new Stopwatch();

            pr = new Process();
            pr.StartInfo = new ProcessStartInfo(@"notepad.exe");
            pr.EnableRaisingEvents = true;
            pr.Exited += new EventHandler(YouClosedNotePad);
            pr.Start();


            aTimer = new System.Timers.Timer();
            aTimer.Interval = 500;
            aTimer.Elapsed += new ElapsedEventHandler(myGong);
            GC.KeepAlive(aTimer);

            Thread myFirstThread;
            myFirstThread = new Thread(new ThreadStart(HelloFirstThread));
            myFirstThread.Start();

            sw.Start();
            aTimer.Enabled = true;

            Console.WriteLine("press [enter] to exit");
            Console.ReadLine();
        }

        static void HelloFirstThread() {
            Console.WriteLine("we're in here now");
            Thread.Sleep(7000);
            if(HasNotepadclosed) {
                Console.WriteLine("bye bye: notepad open");
            } else {
                Console.WriteLine("bye bye: notepad closed");
            }

        }


        static void YouClosedNotePad(object sender, EventArgs e) {
            Console.WriteLine("thanks for closing notepad");
            HasNotepadclosed = true;
        }
        static void myGong(object sender, ElapsedEventArgs e) {
            Console.WriteLine("hello at {0} milliseconds elapsed = {1}", e.SignalTime, sw.ElapsedMilliseconds);
            if(sw.ElapsedMilliseconds > 4000) {
                aTimer.Dispose();
            }
        }


    }
}

如果我在myFirstThread完成睡眠之前关闭记事本,那么我仍然会得到一个最终答案,说“再见:记事本打开”。我需要如何myFirstThread了解原件中发生的事情thread- 这很容易做到吗?

4

1 回答 1

1

我会通过以下方式做到这一点:

  • 将对象传递Process给我需要它所在的线程;
  • 使用WaitForExit方法(可能具有给定的超时值);
于 2013-01-19T21:28:18.017 回答