Search code examples
c#timerstopwatch

C# how to set a timer in method?


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!


Solution

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