C# how to set a timer in method?

356 views Asked by At

I want add a timer in the C# method. When this method execute more than 500 second. the method will throw exception. like this:

if(sw.ElapsedMilliseconds > timeout)
{
break;
}

Do you have any good idea better than StopWatch ? Except Thread. :)

Thank you very much!

1

There are 1 answers

4
nkj On BEST ANSWER

You can use Task with CancellationTokenSource

void LongMethod(CancellationToken token)
{
    for (int i=0; i<51; ++i)
    {
        token.ThrowIfCancellationRequested();
        Thread.Sleep(1000); // some sub operation
    }
}

void Run()
{
    var source = new CancellationTokenSource(50000); // 50 sec delay
    var task = new Task(() => LongMethod(source.Token), source.Token);
    task.Wait();
}