计算执行时间

prv*_*vit 1 .net c# winforms

我需要计算执行某个过程的时间.例如,我想要读取文件中的所有行,但如果它超过5秒,则显示消息框.我应该创建怎样和什么计时器来处理这个"5秒"?

L.B*_*L.B 5

long time=0;

bool b = Task.Factory
            .StartNew(() => time = ExecutionTime(LongRunningTask))
            .Wait(5000);

if (b == false)
{
    MessageBox.Show("Execution took more than 5 seconds.");
}

//time contains the execution time in msec.
Run Code Online (Sandbox Code Playgroud)
public long ExecutionTime(Action action)
{
    var sw = Stopwatch.StartNew();
    action();
    return sw.ElapsedMilliseconds;
}

public void LongRunningTask()
{
    Thread.Sleep(10000);
}
Run Code Online (Sandbox Code Playgroud)