Jorge Ferreira
Jorge Ferreira

Reputation: 97849

How to impose a time limit constraint to an operation

I have a (possibly) lengthy operation a to which I want to impose a limit time constraint t (in milliseconds). If operation a takes less than t milliseconds to complete then I return the answer from operation a; otherwise I want to abort the operation and return a proper error code stating that the time limit constraint was exceeded.

How can I accomplish this in C#? If you have other ideas that are language agnostic feel free to share?

Upvotes: 3

Views: 2704

Answers (4)

trickdev
trickdev

Reputation: 599

There is some material on this already see Implement C# Generic Timeout

The general theme is to have an asynchronous thread (delegate, task etc) to keep an eye on time. Be very careful about Thread.Abort(), you should leave the task running if you can, or use some kind of clean cancellation.

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

Best is to wrap it in a Task<T> or Task and use Wait.

Look here.

Task t = new Task(DoStuff());
t.Wait(1000);

Upvotes: 5

tobias86
tobias86

Reputation: 5029

You could kick off two threads: One for Operation "a", and another with a timer.

If the timer thread finishes, it checks whether the Operation "a" thread has finished. If not, abort the (still running) thread and return your timeout error code.

If Operation "a" finishes before the timer thread does, just kill the timer thread before returning your result.

Upvotes: 2

Sjoerd
Sjoerd

Reputation: 75599

Use BeginInvoke on the method, than after some time check IAsyncResult.IsCompleted. If it is completed, get the result with EndInvoke.

Upvotes: 0

Related Questions