Click here to Skip to main content
15,886,030 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I want to run a function so that if it takes more than 10 seconds I just stop it,
How can I do it?
thanks
Posted
Comments
Sergey Alexandrovich Kryukov 24-Nov-13 11:26am    
Why?
—SA
Member 10304617 24-Nov-13 11:30am    
my function just performs loop with condition ... this condition can exist and can not exist so I want to stop the loop after 10ms that the condition did not exist - in order to prevent an infinite loop.
Sergey Alexandrovich Kryukov 24-Nov-13 11:41am    
I answered. Well, you can do like Solution 2 advises, but this is good only in a very special simple case.
You did not actually answer why do you want it. Pay attention for the last statement in my answer.
—SA

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
 
Share this answer
 
Comments
Member 10304617 25-Nov-13 1:43am    
thanks
There are plenty of examples of how to do it. Pick one...[^]
 
Share this answer
 
Comments
Member 10304617 24-Nov-13 10:43am    
They are very complicated,there is nothing more simple?
Dave Kreskowiak 24-Nov-13 11:17am    
For what you're describing below, no there's no simpler way.
Member 10304617 25-Nov-13 1:43am    
thanks
Well, there are a couple of ways, but they mostly depend on how you are "doing" the function.

If you are just calling a method from a UI control activity (a button click event for example) then pretty much the only way to do it is to save the end time at the beginning of the method:
C#
DateTime endRunAt = DateTime.Now.AddSeconds(10);

And check it at intervals in your code:
C#
foreach (MyClass mc in MyList)
    {
    //... do something to the instance
    if (DateTime.Now > endRunAt) return;
    }
If you are handling it by moving the long-running task into a different thread, then it's slightly more complex: you can set the thread to support cancellation ( for a BackgroundWorker that is the WorkerSupportsCancellation property) and then call CancelAsync on the thread from the main UI when a timer expires. But...that doesn't kill the thread, the thread has to check it's CancellationPending property and kill itself, so the main UI thread can't call CancelAsync and assume that the task is dead - it takes until your code gets to run and notices it should be killing itself - and how long that is depends on how often you code the check in!
 
Share this answer
 
Comments
Member 10304617 24-Nov-13 10:41am    
mmm,my project is console application and I just have a function that read and wait for specific value and I want to stop the function after 10 ms...
OriginalGriff 24-Nov-13 10:54am    
Ooo! That's nasty - Console.ReadLine in particular doesn't have a timeout (and because you are single threaded there's nothing really nice you can do.
Have a look here: http://stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline
It may help - I haven't tried it (I don't deal with user input on console apps much, if at all)
Member 10304617 24-Nov-13 11:24am    
thanks,but my function does not wait to input from the user... my function just performs loop with condition ... this condition can exist and can not exist so I want to stop the loop after 10ms that the condition did not exist - in order to prevent an infinite loop.
How can I do it?(The simplest way)
OriginalGriff 24-Nov-13 11:46am    
Use the Stopwatch class - start it then check the value in the loop - but beware: 10ms is not a long time, and it is entirely possible that your thread could be "side-lined" for longer than that if the system is busy giving you a false detection.
Member 10304617 25-Nov-13 1:43am    
ok,thanks...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900