测量螺纹运行时间

And*_*ind 0 c# multithreading c#-4.0

public void Foo(IRB inR) {
    Stopwatch sw = new Stopwatch();
    sw.Start();

    System.Threading.Thread theThread = new System.Threading.Thread(delegate() {
            if (inR.Ready) {
                inR.ABC();
                while (!inR.Ready) { Thread.Sleep(100); }
            }
            mP.CP = false;
        });
    theThread.Name = "aaabbbccc";
    theThread.Start();
}
Run Code Online (Sandbox Code Playgroud)

所以,我想使用StopWatch测量"theThread"运行的时间.(实际上,我想测量从创建这个线程到线程结束的时间.)我已经把stopwatch.start()放在我想要的地方.但是我应该把我的stopwatch.stop()放在哪里?谢谢.

Jon*_*eet 7

为什么不把秒表代码放在线程本身?例如:

public class ThreadTimer
{
    private readonly ThreadStart realWork;

    public ThreadTimer(ThreadStart realWork)
    {
        this.realWork = realWork;
    }

    public void TimeAndExecute()
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
        try
        {
            realWork();
        }
        finally
        {
            stopwatch.Stop();
            // Log or whatever here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

ThreadStart work = delegate() {
    if (inR.Ready) {
        inR.ABC();
        while (!inR.Ready) { Thread.Sleep(100); }
    }
    mP.CP = false;
};
ThreadTimer timer = new ThreadTimer(work);
Thread thread = new Thread(timer.TimeAndExecute);
thread.Start();
Run Code Online (Sandbox Code Playgroud)