这是我的代码:
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
- 这很容易做到吗?