Re: Setting timeout for methods
From: Jose Solorzano (jhsolorz_at_hotmail.com)
Date: 12/28/04
- Next message: Peter Zwosta: "Declaring and using COM interfaces in C#"
- Previous message: VMI: "off-topic: are there any better file-server DBs than Access?"
- In reply to: ArunPrakash: "Setting timeout for methods"
- Messages sorted by: [ date ] [ thread ]
Date: 28 Dec 2004 10:01:22 -0800
ArunPrakash wrote:
> 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
This is not ideal, but you could create a timeout
handler (needs to be a class probably) that knows
which thread times out (pass Thread.Current when
you create the timeout handler.) In the handler,
instead of throwing an exception, call the Abort()
method on the thread.
Jose Solorzano
- Next message: Peter Zwosta: "Declaring and using COM interfaces in C#"
- Previous message: VMI: "off-topic: are there any better file-server DBs than Access?"
- In reply to: ArunPrakash: "Setting timeout for methods"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|