473,387 Members | 1,575 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Delegates and exceptions

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();
}
}
Nov 15 '05 #1
3 3489
I believe the problem is that the timer and its timeout function run on a
separate thread from the one that started the timer up (see the help page on
Threading.Timer). Because there is no way to specify an exception handler
on that (system created) thread, you cannot catch an exception thrown in the
timeout thread. If possible you might try to place your exception-catch
logic in the timeout function itself.

Perhaps another way:

Have a separate thread ("controller") start the "calculator" on its on
thread. Then in controller, do a
calculator.Join(TimeSpan). In statements following the Join, the
controller can check to see that the calculator thread has completed
normally (via Thread.IsAlive, or a bool set by calculator itself). If not,
controller can put out a message, kill calculator, or do another join to
give it more time.
"Pietje de kort" <wo******@hotmail.com> wrote in message
news:e0*************************@posting.google.co m...
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();
}
}

Nov 15 '05 #2
Pietje,

You have to go about this the opposite way actually. The first thing
you need to do is indicate somewhere if the operation completed or not. You
can use a boolean flag for this. Once you have that, you should expose it
as a property (public or private, it is up to you). You need to place a
lock section around the access of this variable.

After that, in your method, you call your operation asynchronously in
another thread (through the thread pool or a separate thread). In the code
that is performing the work, when complete, set the flag to true.

In the code that calls out to the other thread, after the asynchronous
call is made, you can call the static Sleep method to sleep for the amount
of time you want to wait. If the flag is not set when execution resumes,
you can throw your exception.

Of course, this means that if your operation completes, you have to wait
the same amount of time. In order to get around this, replace the boolean
flag with a WaitHandle, such as an event. In your operation, instead of
setting the boolean flag, set the Event. Also, instead of having the thread
put to sleep, you wait on the handle. Before you wait on the handle, you
set your timer to call back a method and set the event when it calls back.
The flag comes in useful here in the timer method, where you will set it to
true. This way, when the call to WaitOne on the Event is complete, you will
know if it timed out or not.

Hope this helps.
"Pietje de kort" <wo******@hotmail.com> wrote in message
news:e0*************************@posting.google.co m...
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();
}
}

Nov 15 '05 #3
Hi Nicholas,

that's exactly what I found on some MSDN site!
Here's my example code. The actual work is done
in the DoAction method which signals it's done.

Best regards, Wouter van Vugt (not pietje ;) )

using System;
using System.Collections;

using System.IO;
using System.Threading;

namespace TestApp
{
public class TimeoutTest
{
private AutoResetEvent autoEvent;
private int timeout;

public TimeoutTest(int timeout)
{
this.timeout = timeout;
this.autoEvent = new AutoResetEvent(false);
}

public void DoTimeoutAction()
{
Console.WriteLine("Delegating request to work item.");
ThreadPool.QueueUserWorkItem(new WaitCallback(DoAction),null);
Console.WriteLine("Waiting for work item to complete.");
int index = WaitHandle.WaitAny(new AutoResetEvent[]{autoEvent},timeout,false);

if (index == WaitHandle.WaitTimeout)
throw new ApplicationException("Timedout");
Console.WriteLine("Work item completed!");
}

private void DoAction(object state)
{
Console.WriteLine("DL Doing Work...");
Thread.Sleep(5000);
Console.WriteLine("DL Done doing work.");
autoEvent.Set();
}

static void Main()
{
try
{
TimeoutTest t = new TimeoutTest(10000);
t.DoTimeoutAction();
}
catch(ApplicationException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in message news:<us**************@TK2MSFTNGP09.phx.gbl>...
Pietje,

You have to go about this the opposite way actually. The first thing
you need to do is indicate somewhere if the operation completed or not. You
can use a boolean flag for this. Once you have that, you should expose it
as a property (public or private, it is up to you). You need to place a
lock section around the access of this variable.

After that, in your method, you call your operation asynchronously in
another thread (through the thread pool or a separate thread). In the code
that is performing the work, when complete, set the flag to true.

In the code that calls out to the other thread, after the asynchronous
call is made, you can call the static Sleep method to sleep for the amount
of time you want to wait. If the flag is not set when execution resumes,
you can throw your exception.

Of course, this means that if your operation completes, you have to wait
the same amount of time. In order to get around this, replace the boolean
flag with a WaitHandle, such as an event. In your operation, instead of
setting the boolean flag, set the Event. Also, instead of having the thread
put to sleep, you wait on the handle. Before you wait on the handle, you
set your timer to call back a method and set the event when it calls back.
The flag comes in useful here in the timer method, where you will set it to
true. This way, when the call to WaitOne on the Event is complete, you will
know if it timed out or not.

Hope this helps.
"Pietje de kort" <wo******@hotmail.com> wrote in message
news:e0*************************@posting.google.co m...
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();
}
}

Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: 0to60 | last post by:
More importantly, WHY do I wanna do this? Well, I have events that I raise asynchronously like this: foreach(eventhandler handler in eventname.getinvocationlist()) handler.begininvoke(); ...
12
by: AC | last post by:
Hi All, I have been experimenting with delegates and exceptions. I know that when an exception occurs on a separate thread it is saved and retrieved when EndInvoke is called, but why can't I...
4
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on...
30
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment...
6
by: =?Utf-8?B?Sko=?= | last post by:
I have a logger component that logs to multiple sources, ie textfile, eventlog etc. and I have two methods that depending on where I call up my logger comp. one of them will be called. For ex. if...
0
by: bharathreddy | last post by:
Delegates Here in this article I will explain about delegates in brief. Some important points about delegates. This article is meant to only those who already know delegates, it will be a quick...
3
by: rbjorkquist | last post by:
I am looking for some help figuring out the best way to refactor these two examples. I was thinking of using delegates and/or generics; but have little experience with either. Any sample code...
6
by: =?Utf-8?B?T2xkQ2FEb2c=?= | last post by:
My question is regarding the use of delegates in C#. I see how .Net uses delegates to wire event handlers to events. It’s an object created by a single line of code by the system and that makes...
7
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that...
69
by: raylopez99 | last post by:
They usually don't teach you in most textbooks I've seen that delegates can be used to call class methods from classes that are 'unaware' of the delegate, so long as the class has the same...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.