Reputation: 35557
Here is my code:
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();
}
}
}
}
If I close notepad before myFirstThread
has finished sleeping then I still get a final answer saying "bye bye: notepad open". Some how I need to make myFirstThread
aware of what is going on in the original thread
- is this easily done?
Upvotes: 0
Views: 73
Reputation: 16796
I would do that in the following way:
Process
object to the thread that I need it to be in;WaitForExit
methods (possibly with a given timeout value);Upvotes: 1