0

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!

Shukun
  • 45
  • 5
  • 2
    What's wrong with what you're using? – Blorgbeard Nov 19 '14 at 03:13
  • 1
    possible duplicate of [Set timeout to an operation](http://stackoverflow.com/questions/2265412/set-timeout-to-an-operation) – Diligent Key Presser Nov 19 '14 at 03:19
  • The code you showed simply breaks out of a loop, not throws an exception as you stated. What behavior _specifically_ are you looking to achieve here? What is it about comparing the elapsed time to a timeout value is it that doesn't address your specific need? – Peter Duniho Nov 19 '14 at 04:56
  • 1
    There are 2 approaches, either method itself is measuring timeout and terminates itself (as you do it already by using `StopWatch`) or method is *cancel-able* (in this case you can cancel it by using something what counting timeout in parallel with its execution - `Timer`, `Thread`, `Task`, etc). If method is *black box* (you can't modify it and it doesn't support cancel request), then you are talking about *terminating*. There are few possibilities to terminate running code, but none is recommended. Could you provide more details please about what is your case? – Sinatr Nov 19 '14 at 10:23

1 Answers1

2

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();
}
nkj
  • 81
  • 1
  • 5
  • 1
    -1 because it's generally a bad idea to use Thread.Sleep, especially for timing. See http://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful for more info. A better solution is to use a `Timer`. – Xcelled Nov 19 '14 at 03:25
  • Oh, my bad. I misread your answer. Disregard my comment :) If you make a trivial edit to your post, I'll be able to rescind my downvote. – Xcelled Nov 19 '14 at 03:30
  • 1
    My -1 has become a +1. – Xcelled Nov 19 '14 at 03:54
  • Thanks all guys. I used Thread.Sleep(). Especially thanks Xcelled194. I use it to unit test, it's acceptable. – Shukun Nov 20 '14 at 02:45