2012-12-10 114 views
1

我需要计算执行某个进程的时间。例如,我想读取文件中的所有行,但是如果它超过5秒,则显示messagebox。我应该如何创建定时器,并处理这个“5秒”?计算执行时间

+3

http://www.codeproject.com/Articles/31691/Timeout-Functions#execute_within_timelimit –

+0

踢只读文件开了一个新的线程,并在主线程跟踪所经过的时间。 –

回答

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); 
    } 
} 
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" 
+0

考虑,这个例子只会显示需要多少时间.. – prvit

+0

@ProkopchukVitaliy你说过“我需要计算执行某个过程的时间”,这就是我的回答。我会很快回答你的其他问题。 –

+0

@ProkopchukVitaliy现在查看我的编辑。 –

0
long time1; 
Stopwatch sw = new Stopwatch(); 

sw.Start(); 
... 
time = sw.ElapsedTicks; 
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); 
} 
+0

看起来不错,将尝试这个例子,谢谢 – prvit

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 
} 
+0

它似乎检查时间,只有在读取行后,我需要做的像一个“simulteniously “ – prvit

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. 
}