prvit
prvit

Reputation: 966

Calculate time of executing

I need to calculate the time of executing some process. For example i want to read all lines from a file, but if it's going more than 5 sec, to show messagebox, for example. How and what timer should i create, to handle this "5 sec"?

Upvotes: 1

Views: 1014

Answers (6)

IdahoSixString
IdahoSixString

Reputation: 643

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);
    }
}

Upvotes: 0

maxim pg
maxim pg

Reputation: 701

Consider the following approach:

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

Upvotes: 0

L.B
L.B

Reputation: 116118

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);
}

Upvotes: 5

Shadow Wizard
Shadow Wizard

Reputation: 66389

Use the Stopwatch class: (part of System.Diagnostics namespace)

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"

Upvotes: 1

Watlaoyeh
Watlaoyeh

Reputation: 38

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
}

Upvotes: 0

phoniq
phoniq

Reputation: 238

long time1;
Stopwatch sw = new Stopwatch();

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

Upvotes: 0

Related Questions