1

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

4

6 回答 6

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);
}
于 2012-12-10T14:10:45.450 回答
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"
于 2012-12-10T14:03:01.033 回答
0
long time1;
Stopwatch sw = new Stopwatch();

sw.Start();
...
time = sw.ElapsedTicks;
于 2012-12-10T14:06:00.360 回答
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
}
于 2012-12-10T14:14:00.547 回答
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.
}
于 2012-12-10T19:10:17.560 回答
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);
    }
}
于 2014-03-26T22:00:51.767 回答