2013-01-19 32 views
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中發生了什麼 - 這很容易完成嗎?

回答

1

我會做下列方式:

  • 傳遞Process對象,我需要它是在線程;
  • 使用WaitForExit方法(可能具有給定的超時值);
+0

...所以'PR'需要傳遞給'myFirstThread'?:如何修改我現有的代碼來做到這一點? – whytheq

+0

whoops - 我認爲代碼有錯誤if(HasNotepadclosed){'should be'if(HasNotepadclosed == false){';然後似乎工作正常 – whytheq