This is a wrong idea. Even though it is possible, such timeout should not be associated with certain function. (And there is no such concept as function timeout.) Even if you try to do it at the level of the function, it will be prohibitively limiting. How this function could call other functions? Only by embedding the same mechanism in all functions called, recursively? No, such timeout can be applied only to ha thread, but even in this case, this is not easy.
The first seemingly apparent method would be aborting the thread by timeout be calling
System.Threading.Thread.Abort
is some other thread. But let's see how uneasy and dangerous it can be. First of all, if you need to guarantee this timeout with any reasonable certainty, you would need… at least two additional thread, not one: one thread is "measuring" the timeout by calling
System.Threading.Thread.Sleep
and than calls
Abort
, and another thread is the one being aborted. And the similar solution is using a
timer instead of the first thread, which is not simpler. More importantly, having a thread aborted can be
dangerous, due to several reasons. Some dangers could be eliminated by proper handling of the event
System.Threading.ThreadAbortException
:
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception%28v=vs.110%29.aspx[
^].
Doing such thing requires very good understanding of what you are doing and is also not always a solution. In particular, it's is extremely dangerous to allow abortion when you call a constructor of any complex object. Doing so could result in a partially constructed object, the situation which, in certain situations, is hard to recover from (and may be even impossible if allocation of unmanaged resources is involved). You can develop a mechanism of temporary blocking (or even more complex mechanism, for postponing) of abortion through indirect abortion call via the use of thread synchronization in between, but this mechanism would contradict to your timing requirement.
I don't want event discuss other ways of exiting the thread (or a function), as they would be
cooperative and hence contradict to the timing requirement. No matter how you do it, it would require periodic check-up of the elapsed time. Not only it could be wasteful, but you might never reach your goal, because you cannot guarantee that all time periods between the checks can be short enough. What's the use to check time every, say, 0.1 s, if you have a chance to call a function which itself could take 20 seconds? So, such approach is possible, but only to in a special situation, cannot be universal, ever.
Overall, I would say that if you feel that such requirement is important for your application, your general application design goes in a wrong direction. If you want, we can discuss this aspect, too.
—SA