计算执行时间

时间:2012-12-10 14:00:23

标签: c# .net winforms

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

6 个答案:

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

public long ExecutionTime(Action action)
{
    var sw = Stopwatch.StartNew();
    action();
    return sw.ElapsedMilliseconds;
}

public void LongRunningTask()
{
    Thread.Sleep(10000);
}

答案 1 :(得分:1)

使用Stopwatch类:( System.Diagnostics命名空间的一部分)

Stopwatch watch = new Stopwatch();
watch.Start();
while (someCond) {
    if (watch.Elapsed.TotalSeconds >= 5) {
        MessageBox.Show("Process taking too much time, aborting");
        break;
    }
    //keep looping
}
watch.Stop();
string msg = "Process took " + watch.Elapsed.TotalSeconds + " seconds to complete"

答案 2 :(得分:0)

long time1;
Stopwatch sw = new Stopwatch();

sw.Start();
...
time = sw.ElapsedTicks;

答案 3 :(得分:0)

using System.Diagnostic
using System.Window.Forms

//your code
Stopwatch watch = new Stopwatch();
watch.Start();

// start reading lines of a file using file system object

watch.Stop();

if(watch.Elapsed.ElapsedMilliseconds>5000)
{
   MessageBox.Show("The process takes more than 5 seconds !!!");
}
else
{
   // your business logic
}

答案 4 :(得分:0)

考虑以下方法:

var cts = new CancellationTokenSource();
var task = new Task(YourLongRunningOperation, cts.Token);
task.Start();

var delayTask = Task.Delay(5000);

try
{
    await Task.WhenAny(task, delayTask);
    if(!task.IsCompleted)
    {
        cts.Cancel();
        // You can display a message here.
        await task;
    }
}
catch(OperationCanceledException cex)
{
    // TODO Handle cancelation.
}
catch (AggregateException aex)
{
    // TODO Handle exceptions.
}

if(task.IsCanceled && delayTask.IsCompleted)
{
    // TODO Display a long running error message.
}

答案 5 :(得分:0)

class Program
{
    static void Main()
    {
        bool result = Task.Factory.StartNew(SomePossibleFailingTask).Wait(1000);

        if (result == false)
        {
            Console.WriteLine("Something has gone wrong!");
        }

        Console.ReadKey();
    }

    public static void SomePossibleFailingTask()
    {
        Thread.Sleep(15000);
    }
}