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 に答える