测量螺纹运行时间

时间:2012-01-09 19:05:08

标签: 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();
}

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

2 个答案:

答案 0 :(得分: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
        }
    }
}

然后:

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();

答案 1 :(得分:1)

你能把它放在代表的最后吗?
如果将Stopwatch对象创建为函数本地变量,则必须将后台线程与正在运行的线程连接。或者,您可以在函数外部创建它以使线程无需连接即可运行。

public void ConditionPlate(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;

        // ********************************
        // This will stop the stopwatch.
        // ********************************
        sw.Stop();
    });
    theThread.Name = "aaabbbccc";
    theThread.Start();

    // Wait for the thread to stop (necessary if 'sw' is created here, locally)
    theThread.Join();

    // gets time required for creation of thread to thread completion.
    var elapsed = sw.Elapsed;

}
相关问题