Hi,
I want to implement a method which will poll database for messages.
But i want to provide a method that will specify a timeout until which
it will be polled and after that it will throw an exception. I tried
the following code.
Here say for example GetString in class test is a method for which i
want to provide timeout. Class1 contains the console application's main
method
using System;
using System.Threading;
using System;
using System.Threading;
namespace ConsoleApplication6
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
test t1 = new test();
try
{
string s = t1.GetString( 100, new TimeSpan( 1000 ) );
Console.WriteLine( s );
}
catch( Exception ex )
{
Console.WriteLine( "handled " + ex.Message );
}
//
// TODO: Add code to start application here
//
}
}
class test
{
public string GetString( int count )
{
string s = "";
for( int i = 0; i < count; i++ )
Console.WriteLine(i);
return s;
}
public string GetString( int count, TimeSpan timeout )
{
Timer tmr = new Timer( new TimerCallback( Timedout ), null,
(long)timeout.TotalMilliseconds, Timeout.Infinite );
return GetString( count );
}
void Timedout( object state )
{
throw new ApplicationException("Time out" );
}
}
}
The problem with the above code is control does not come to catch block
in the main method. Where is the exception thrown? When you run the
sample you get the message exception in the console window but the
method still continues. I want to the stop the method execution when
the exception occurs. Can somebody help?
Thanks & Regards,
Arun Prakash