P
Pietje de kort
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.Threading.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 UncaughtException event)?
Best regards Wouter
using System.Threading;
public class Test
{
public Test(){};
public DoTimeoutAction()
{
Timer timer = new Timer(new TimerCallback(Timedout),null,
1000,Timeout.Infinite);
Console.WriteLine("Doing something");
Thread.Sleep(5000); // will cause timeout to occur
Console.WriteLine("Done doing something");
timer.Dispose(); // stop timer
}
private void Timedout(object state)
{
throw new ApplicationException("Timeout occured.");
}
static void Main()
{
Test t = new Test();
try
{
t.DoTimeoutAction();
}catch(ApplicationException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Done!");
Console.ReadLine();
}
}
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.Threading.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 UncaughtException event)?
Best regards Wouter
using System.Threading;
public class Test
{
public Test(){};
public DoTimeoutAction()
{
Timer timer = new Timer(new TimerCallback(Timedout),null,
1000,Timeout.Infinite);
Console.WriteLine("Doing something");
Thread.Sleep(5000); // will cause timeout to occur
Console.WriteLine("Done doing something");
timer.Dispose(); // stop timer
}
private void Timedout(object state)
{
throw new ApplicationException("Timeout occured.");
}
static void Main()
{
Test t = new Test();
try
{
t.DoTimeoutAction();
}catch(ApplicationException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Done!");
Console.ReadLine();
}
}