Hello all,
I want to implement Timeout behaviour in a class of mine. When a
method is called it should timeout after a few seconds. To do this
I've built a
System.Threadin g.Timer that calls a delegate method after x milli's,
the called
delegate throws an exception indicating timeout.
The big problem is my code will not catch the thrown exception because
it
is generated outside of normal program control. Is there any way to
catch the
exception thrown (other than hooking the UncaughtExcepti on event)?
Best regards Wouter
using System.Threadin g;
public class Test
{
public Test(){};
public DoTimeoutAction ()
{
Timer timer = new Timer(new TimerCallback(T imedout),null,
1000,Timeout.In finite);
Console.WriteLi ne("Doing something");
Thread.Sleep(50 00); // will cause timeout to occur
Console.WriteLi ne("Done doing something");
timer.Dispose() ; // stop timer
}
private void Timedout(object state)
{
throw new ApplicationExce ption("Timeout occured.");
}
static void Main()
{
Test t = new Test();
try
{
t.DoTimeoutActi on();
}catch(Applicat ionException e)
{
Console.WriteLi ne(e.Message);
}
Console.WriteLi ne("Done!");
Console.ReadLin e();
}
}
I want to implement Timeout behaviour in a class of mine. When a
method is called it should timeout after a few seconds. To do this
I've built a
System.Threadin g.Timer that calls a delegate method after x milli's,
the called
delegate throws an exception indicating timeout.
The big problem is my code will not catch the thrown exception because
it
is generated outside of normal program control. Is there any way to
catch the
exception thrown (other than hooking the UncaughtExcepti on event)?
Best regards Wouter
using System.Threadin g;
public class Test
{
public Test(){};
public DoTimeoutAction ()
{
Timer timer = new Timer(new TimerCallback(T imedout),null,
1000,Timeout.In finite);
Console.WriteLi ne("Doing something");
Thread.Sleep(50 00); // will cause timeout to occur
Console.WriteLi ne("Done doing something");
timer.Dispose() ; // stop timer
}
private void Timedout(object state)
{
throw new ApplicationExce ption("Timeout occured.");
}
static void Main()
{
Test t = new Test();
try
{
t.DoTimeoutActi on();
}catch(Applicat ionException e)
{
Console.WriteLi ne(e.Message);
}
Console.WriteLi ne("Done!");
Console.ReadLin e();
}
}
Comment