我需要计算执行某个进程的时间。例如,我想读取文件中的所有行,但是如果它超过5秒,则显示messagebox。我应该如何创建定时器,并处理这个“5秒”?计算执行时间
计算执行时间
回答
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);
}
}
使用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"
考虑,这个例子只会显示需要多少时间.. – prvit
@ProkopchukVitaliy你说过“我需要计算执行某个过程的时间”,这就是我的回答。我会很快回答你的其他问题。 –
@ProkopchukVitaliy现在查看我的编辑。 –
long time1;
Stopwatch sw = new Stopwatch();
sw.Start();
...
time = sw.ElapsedTicks;
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);
}
看起来不错,将尝试这个例子,谢谢 – prvit
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
}
它似乎检查时间,只有在读取行后,我需要做的像一个“simulteniously “ – prvit
考虑以下方法:
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.
}
- 1. 计算的执行时间
- 2. 计算CPU执行时间
- 3. 执行时间计算
- 4. pthread执行时间?如何计算?
- 5. 计算的方法的执行时间
- 6. 计算SQL查询的执行时间?
- 7. Cassandra查询执行时间计算
- 8. 程序执行的时间计算?
- 9. 的Java计算平均执行时间
- 10. 如何计算执行时间
- 11. 计算Java程序的执行时间
- 12. 执行时间计算有多准确?
- 13. php如何计算执行时间?
- 14. 计算Excel电子表格计算的执行时间?
- 15. 如何设置计算执行时间的计时器
- 16. JAVA:计算运行时错误的执行时间
- 17. 执行计算
- 18. 执行计算
- 19. 如何知道在C++中计算算法的执行时间?
- 20. 计算一个算法的执行时间
- 21. 计算一行或多行代码的执行时间
- 22. 运行时间计算
- 23. joblib并行计算时间
- 24. 计算运行时间
- 25. JTable运行时间计算?
- 26. 如何计算可执行文件的运行时间?
- 27. PHP计算的执行时间,有时返回负值
- 28. 执行Linq查询时的时间距离条件计算
- 29. 执行计算值
- 30. 执行计算ACCESS
http://www.codeproject.com/Articles/31691/Timeout-Functions#execute_within_timelimit –
踢只读文件开了一个新的线程,并在主线程跟踪所经过的时间。 –