How do you want to terminate execution? Do you want to exit the program, or just stop searching? If you're okay with destroying your process, you could do this:
var timer = new Timer(new TimeSpan(0, 0, 400));
timer.Elapsed += { throw new Exception("Time's up!"); }
timer.Start();
doSearch();
timer.Stop();
But I think you want something more reasonable. In that case, you probably have to do this within doSearch
itself. I assume that the method is iterative or recursive, in which case you can store the start time in an instance variable, then check the elapsed time at a well-known point in the iteration/recursion. For example:
private DateTime _start;
private TimeSpan _maxTime = new TimeSpan(0, 0, 400);
public void TimedSearch()
{
_start = DateTime.Now;
DoSearch();
}
public void DoSearch()
{
while (notFound)
{
if (DateTime.Now - _start > _maxTime)
return;
// search code
}
}