473,652 Members | 3,132 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exceptions Thrown in Background Threads

Consider:

[begin code]

void Start()
{
if (!TryToDoSometh ing())
ShowErrorMessag e();
}

void TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething);
thread.IsBackgr ound = true;
thread.Start();

return true;
}
catch (SomeException)
{
return false;
}
}

void DoSomething()
{
DoSomethingWhic hMightThrowASom eException();
}

[end code]

Trying to catch the SomeException in TryToDoSomethin g doesn't seem to work,
presumably because the exception is thrown in a separate thread. Is this
correct?

If so, what's the best was of dealing with this exception so that I can
call ShowErrorMessag e in the main thread when it's thrown?
Nov 16 '05 #1
10 8557
Trying to catch the SomeException in TryToDoSomethin g doesn't seem to work, presumably because the exception is thrown in a separate thread. Is this
correct?
That is correct. You must catch the exception on which it is thrown.

If so, what's the best was of dealing with this exception so that I can
call ShowErrorMessag e in the main thread when it's thrown?


Here's a way to do that for purposes of illustration; I would not actually
do it this way.

private Exception theException = null;
void MainEntryPointT oTryToDoSomethi ng()
{
Thread thread = new Thread(new ThreadStart(DoS omething);
thread.IsBackgr ound = true;
thread.Start();
thread.Join(); // wait until thread terminates
if ( theException != null )
ShowErrorMessag e(theException) ;
}

void DoSomething()
{
try
{
DoSomethingWhic hMightThrowAnEx ception();
|}
catch(Exception ex)
{
theException = ex; // save it
}
}
Basically the idea is the save the exception object so that it is available
to the thread which will display the error message. This example used a
global variable, theException. A better way to handle this is to use the
Async pattern as used by the BCL
Note also that you must use thread.Join, or some other synchronization
primitive such as an async callback, to correctly rendevous when the thread
is done.

Nov 16 '05 #2
David Levine wrote:
Here's a way to do that for purposes of illustration; I would not actually
do it this way.
I like the simplicity of this solution. Why wouldn't you do it this way --
is it a bad idea?
A better way to handle this is to use the
Async pattern as used by the BCL


Hmm... I've never heard of this. Google didn't turn up anything, either.

Thanks for the help.
Nov 16 '05 #3
Cool Guy wrote:
Consider:

[begin code]

void Start()
{
if (!TryToDoSometh ing())
ShowErrorMessag e();
}

void TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething);
thread.IsBackgr ound = true;
thread.Start();

return true;
}
catch (SomeException)
{
return false;
}
}

void DoSomething()
{
DoSomethingWhic hMightThrowASom eException();
}

[end code]

Trying to catch the SomeException in TryToDoSomethin g doesn't seem to
work, presumably because the exception is thrown in a separate
thread. Is this correct?
Yes.
If so, what's the best was of dealing with this exception so that I
can call ShowErrorMessag e in the main thread when it's thrown?


Use events. Assume you have a class "Main", which controls your
application's main thread (e.g. a Windows Form), and a class "Worker" that
performs lengthy operations on a separate thread to avoid blocking Main's
thread. If Worker exposes an event "Error", which is triggered whenever an
exception needs to be communicated to Worker's owner, Main can simply
subscribe to the Error event through standard event handling:

/* Note that ErrorEventArgs and ErrorEventHandl er do already exist in
System.IO */

class Main {
private Worker worker;

public Main() {
this.worker = new Worker();
this.worker.Err or += new ErrorEventHandl er(this.Worker_ Error);
}

private void Worker_Error(ob ject sender, ErrorEventArgs e) {
// CAVEAT: If this is a WinForm class, first marshal the call
// back to the UI thread!
// Do something... display message, log to file, etc.
}
}

class Worker {
public event ErrorEventHandl er Error;

public void Work() {
// kick off DoWork() in another thread
}

protected virtual void OnError(ErrorEv entArgs e) {
ErrorEventHandl er handler = Error;
if (handler != null) {
handler(this, e);
}
}

private void DoWork() {
try {
// heavy stuff...
}
catch (Exception ex) {
OnError(new ErrorEventArgs( ex));
}
}
}

Of course this approach allows to to communicate anything back to Main,
including completion results of Work(). Plus, it nicely abstracts from how
Work() actually makes DoWork() run on another thread... whether it uses its
own managed thread, an async delegate, whatever -- the approach is the same.

Note the CAVEAT comment in Worker_Error: If you use this approach in Windows
Forms apps, you *must* protect all such callbacks by assuring each call is
marshalled back to the UI thread if necessary, using Control.InvokeR equired
and Control.Invoke( ).

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Nov 16 '05 #4

"Cool Guy" <co*****@abc.xy z> wrote in message
news:9g******** *******@cool.gu y.abc.xyz...
David Levine wrote:
Here's a way to do that for purposes of illustration; I would not
actually
do it this way.


I like the simplicity of this solution. Why wouldn't you do it this
way --
is it a bad idea?
A better way to handle this is to use the
Async pattern as used by the BCL


Hmm... I've never heard of this. Google didn't turn up anything, either.


Here is a sample running a thread proc on a threapool thread using async
delegates. Check msdn for details.

using System;
using System.Threadin g;
// Async delegate
public delegate void Proc(StateObjec t o);

public class Forked {
static void Worker(StateObj ect o) {
Console.WriteLi ne("Thread {0}, executing Worker, " + "is {1}from the
thread pool.",Thread.C urrentThread.Ge tHashCode(),
Thread.CurrentT hread.IsThreadP oolThread ? "" : "not ");
int r;
int y = 0;
r = 10/y; // Do something really nasty
}

public static void Main() {
Proc proc = new Proc(Worker);
// Do some work using an async. delegate (running on a threadpool thread)
IAsyncResult call = proc.BeginInvok e(null, null, null);
// Do some other work .....
Console.WriteLi ne("Primary thread {0}",
Thread.CurrentT hread.GetHashCo de());
try {
//Asynch. Rendez-vous. Just call EndInvoke at some point within a try
block and you'll see the exception.
proc.EndInvoke( call);
}
catch (Exception ex) {
Console.WriteLi ne("{0}", ex.Message);
}
}
}
Willy.
Nov 16 '05 #5
On second thoughts, this wouldn't work in my situation, because I need to
leave MainEntryPointT oTryToDoSomethi ng after the call to Thread.Start if an
exception isn't thrown.

At current, MainEntryPointT oTryToDoSomethi ng waits until the thread is
finished even if an exception isn't thrown.

I guess I'll have to use events like Joerg suggested. Or is this possible
with some other method?
Nov 16 '05 #6
Hi Cool Guy,

You can set up a global exception handler, similar to this:

using System;
using System.Threadin g;

public class Test
{
public void GlobalException Handler(object sender,
UnhandledExcept ionEventArgs e)
{
Console.WriteLi ne(e.ExceptionO bject.ToString( ));
}

public static void Main()
{
Test t = new Test();
AppDomain.Curre ntDomain.Unhand ledException += new
UnhandledExcept ionEventHandler (t.GlobalExcept ionHandler);
t.Start();
}
void Start()
{
if (!TryToDoSometh ing())
Console.WriteLi ne("!TryToDoSom ething()");
}

bool TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething));
thread.IsBackgr ound = true;
thread.Start();

thread.Join();

return true;
}
catch (ApplicationExc eption)
{
return false;
}
}

void DoSomething()
{
throw new ApplicationExce ption("Test Exception");
}
}

Joe
--
Joe Mayo, Author/Instructor
Need C#/.NET training?
visit www.mayosoftware.com
C# Tutorial - www.csharp-station.com

"Cool Guy" <co*****@abc.xy z> wrote in message
news:56******** *******@cool.gu y.abc.xyz...
Consider:

[begin code]

void Start()
{
if (!TryToDoSometh ing())
ShowErrorMessag e();
}

void TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething);
thread.IsBackgr ound = true;
thread.Start();

return true;
}
catch (SomeException)
{
return false;
}
}

void DoSomething()
{
DoSomethingWhic hMightThrowASom eException();
}

[end code]

Trying to catch the SomeException in TryToDoSomethin g doesn't seem to work, presumably because the exception is thrown in a separate thread. Is this
correct?

If so, what's the best was of dealing with this exception so that I can
call ShowErrorMessag e in the main thread when it's thrown?

Nov 16 '05 #7
I would recommend not doing it this way. All the other mechanisms provide
the opportunity to respond to the exception when it occurs; or if the
handler is deferred, then another opportunity to handle it occurs when
EndInvoke is called. Also, the timing between catch handlers and finally
blocks are run is well defined.

One problem with using the unhandled exception handler is that the
notification occurs after the ability to respond to the exception has past.
If the exception were to occur on the main thread or a thread that
originated in unmanaged code, then in the 1.1 runtime the application will
terminate immediately after the unhandled event it delivered. In future
versions of the runtime the app may terminate even if the exception occurred
on a worker thread (it may even be a configurable policy decision of the
app). Regardless, I would not rely on this working consistently across
multiple versions of the runtime.

More subtle issues may arise when there are timing constraints between when
an exception occurs, when it is handled, and when finally blocks are run.
Handling an exception from an unhandled exception handler adds to the number
of code paths and changes the timing of when the event is delivered and when
finally blocks are run. This may not be a problem, but then again...
"Joe Mayo [C# MVP]" <jm***@nospamAt CSharpDashStati on.com> wrote in message
news:eH******** ******@TK2MSFTN GP09.phx.gbl...
Hi Cool Guy,

You can set up a global exception handler, similar to this:

using System;
using System.Threadin g;

public class Test
{
public void GlobalException Handler(object sender,
UnhandledExcept ionEventArgs e)
{
Console.WriteLi ne(e.ExceptionO bject.ToString( ));
}

public static void Main()
{
Test t = new Test();
AppDomain.Curre ntDomain.Unhand ledException += new
UnhandledExcept ionEventHandler (t.GlobalExcept ionHandler);
t.Start();
}
void Start()
{
if (!TryToDoSometh ing())
Console.WriteLi ne("!TryToDoSom ething()");
}

bool TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething));
thread.IsBackgr ound = true;
thread.Start();

thread.Join();

return true;
}
catch (ApplicationExc eption)
{
return false;
}
}

void DoSomething()
{
throw new ApplicationExce ption("Test Exception");
}
}

Joe
--
Joe Mayo, Author/Instructor
Need C#/.NET training?
visit www.mayosoftware.com
C# Tutorial - www.csharp-station.com

"Cool Guy" <co*****@abc.xy z> wrote in message
news:56******** *******@cool.gu y.abc.xyz...
Consider:

[begin code]

void Start()
{
if (!TryToDoSometh ing())
ShowErrorMessag e();
}

void TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething);
thread.IsBackgr ound = true;
thread.Start();

return true;
}
catch (SomeException)
{
return false;
}
}

void DoSomething()
{
DoSomethingWhic hMightThrowASom eException();
}

[end code]

Trying to catch the SomeException in TryToDoSomethin g doesn't seem to

work,
presumably because the exception is thrown in a separate thread. Is this correct?

If so, what's the best was of dealing with this exception so that I can
call ShowErrorMessag e in the main thread when it's thrown?


Nov 16 '05 #8
Thanks, that's exactly what I had in mind.

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:%2******** *******@TK2MSFT NGP12.phx.gbl.. .

"Cool Guy" <co*****@abc.xy z> wrote in message
news:9g******** *******@cool.gu y.abc.xyz...
David Levine wrote:
Here's a way to do that for purposes of illustration; I would not
actually
do it this way.
I like the simplicity of this solution. Why wouldn't you do it this
way --
is it a bad idea?
A better way to handle this is to use the
Async pattern as used by the BCL


Hmm... I've never heard of this. Google didn't turn up anything, either.


Here is a sample running a thread proc on a threapool thread using async
delegates. Check msdn for details.

using System;
using System.Threadin g;
// Async delegate
public delegate void Proc(StateObjec t o);

public class Forked {
static void Worker(StateObj ect o) {
Console.WriteLi ne("Thread {0}, executing Worker, " + "is {1}from the
thread pool.",Thread.C urrentThread.Ge tHashCode(),
Thread.CurrentT hread.IsThreadP oolThread ? "" : "not ");
int r;
int y = 0;
r = 10/y; // Do something really nasty
}

public static void Main() {
Proc proc = new Proc(Worker);
// Do some work using an async. delegate (running on a threadpool

thread) IAsyncResult call = proc.BeginInvok e(null, null, null);
// Do some other work .....
Console.WriteLi ne("Primary thread {0}",
Thread.CurrentT hread.GetHashCo de());
try {
//Asynch. Rendez-vous. Just call EndInvoke at some point within a try
block and you'll see the exception.
proc.EndInvoke( call);
}
catch (Exception ex) {
Console.WriteLi ne("{0}", ex.Message);
}
}
}
Willy.

Nov 16 '05 #9
"David Levine" <no************ ****@wi.rr.com> wrote in message
news:uV******** ******@TK2MSFTN GP15.phx.gbl...
I would recommend not doing it this way. All the other mechanisms provide
the opportunity to respond to the exception when it occurs; or if the
handler is deferred, then another opportunity to handle it occurs when
EndInvoke is called. Also, the timing between catch handlers and finally
blocks are run is well defined.
It appears that an asynchronous delegate was an acceptable solution for OP,
but this isn't always the case. There are times when people need to use a
normal thread, rather than an asynchronous delegate. A specific exception
may be handled on the thread where code can be wrapped in a try/catch block.
However, it isn't practical to write catch blocks for every possible
exception that can be raised. The global exeption handler can serve as a
backup mechanism to keep your program from crashing because of unhandled
exceptions. The decision on whether to catch System.Exceptio n may or may
not have anything to do with timing between catch and finally blocks,
depending on the application.
One problem with using the unhandled exception handler is that the
notification occurs after the ability to respond to the exception has past.

I think it depends on the application as to whether this matters or not.
If the exception were to occur on the main thread or a thread that
originated in unmanaged code, then in the 1.1 runtime the application will
terminate immediately after the unhandled event it delivered.
Sure, global exeption handlers are for managed code. The fact that some
unmanaged code might crash the CLR still doesn't convince me that I
shouldn't use a global exception handler.
In future
versions of the runtime the app may terminate even if the exception occurred on a worker thread (it may even be a configurable policy decision of the
app). Regardless, I would not rely on this working consistently across
multiple versions of the runtime.
Why would you not rely on this working consistently across multiple versions
of the runtime? Microsoft explains how this is done through their
architectural guidance document "Exception Management in .NET":

http://msdn.microsoft.com/library/de...ceptdotnet.asp

I'm open minded enough to hear new ideas and if you have information that
would change my mind, then I'm interested in hearing it.
More subtle issues may arise when there are timing constraints between when an exception occurs, when it is handled, and when finally blocks are run.
Handling an exception from an unhandled exception handler adds to the number of code paths and changes the timing of when the event is delivered and when finally blocks are run. This may not be a problem, but then again...
Right. It could be a problem, i.e. in cases where you caught a specific
exception and want capture some information before disposing a resource.
However, I don't see that as a reason not to have a global exception
handler.


"Joe Mayo [C# MVP]" <jm***@nospamAt CSharpDashStati on.com> wrote in message
news:eH******** ******@TK2MSFTN GP09.phx.gbl...
Hi Cool Guy,

You can set up a global exception handler, similar to this:

using System;
using System.Threadin g;

public class Test
{
public void GlobalException Handler(object sender,
UnhandledExcept ionEventArgs e)
{
Console.WriteLi ne(e.ExceptionO bject.ToString( ));
}

public static void Main()
{
Test t = new Test();
AppDomain.Curre ntDomain.Unhand ledException += new
UnhandledExcept ionEventHandler (t.GlobalExcept ionHandler);
t.Start();
}
void Start()
{
if (!TryToDoSometh ing())
Console.WriteLi ne("!TryToDoSom ething()");
}

bool TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething));
thread.IsBackgr ound = true;
thread.Start();

thread.Join();

return true;
}
catch (ApplicationExc eption)
{
return false;
}
}

void DoSomething()
{
throw new ApplicationExce ption("Test Exception");
}
}

Joe
--
Joe Mayo, Author/Instructor
Need C#/.NET training?
visit www.mayosoftware.com
C# Tutorial - www.csharp-station.com

"Cool Guy" <co*****@abc.xy z> wrote in message
news:56******** *******@cool.gu y.abc.xyz...
Consider:

[begin code]

void Start()
{
if (!TryToDoSometh ing())
ShowErrorMessag e();
}

void TryToDoSomethin g()
{
try
{
Thread thread = new Thread(new ThreadStart(DoS omething);
thread.IsBackgr ound = true;
thread.Start();

return true;
}
catch (SomeException)
{
return false;
}
}

void DoSomething()
{
DoSomethingWhic hMightThrowASom eException();
}

[end code]

Trying to catch the SomeException in TryToDoSomethin g doesn't seem to

work,
presumably because the exception is thrown in a separate thread. Is this correct?

If so, what's the best was of dealing with this exception so that I can call ShowErrorMessag e in the main thread when it's thrown?



Nov 16 '05 #10

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

Similar topics

26
2887
by: OvErboRed | last post by:
I just read a whole bunch of threads on microsoft.public.dotnet.* regarding checked exceptions (the longest-running of which seems to be <cJQQ9.4419 $j94.834878@news02.tsnz.net>. My personal belief is that checked exceptions should be required in .NET. I find that many others share the same views as I do. It is extremely frustrating to have to work around this with hacks like Abstract ADO.NET and CLRxLint (which still don't solve the...
24
2487
by: mag31 | last post by:
Is there any way to find out if a particular .net function will throw an exception without first generating the exception? I am using structured exception handling i.e. try catch finally blocks with a top level catch all for Exception. However, I would like to be able to catch most .net exceptions when they are generated. I would then be able to generate a valuable exception message and do something about it!!! Hence the question above....
6
2823
by: RepStat | last post by:
I've read that it is best not to use exceptions willy-nilly for stupid purposes as they can be a major performance hit if they are thrown. But is it a performance hit to use a try..catch..finally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..finally blocks that must be robust, in order that cleanup can be done correctly should there be an exception?
5
3804
by: Miyra | last post by:
Hi. I'm working with an app that uses exceptions for control flow. These are code blocks where exceptions are thrown/caught regularly. A couple hundred exceptions occur per hour and they're caught close to the point of origination. I'm trying to decide whether to refactor... What is the cost of throwing an exception in the CLR - relative to, say, a conditional statement? Are we taking talking 1+ orders of magnitude? Is there...
5
2806
by: Jakub Moskal | last post by:
Hi, I want to write a benchmark that will measure performance of several different algorithms for the same problem. There is a set time bound though, the algorithm cannot run longer than n minutes. Here is what the main program would do: initializeVariables(); try
2
1448
by: Alex | last post by:
Hi Is it possible to catch exceptions thrown by a System.Threading.Thread object? i.e. I have an instance of a class that is created using the normal Thread/ThreadStart method, but once it starts, there will be no try/catch block to catch any exceptions thrown (other than the ones that might be raised by the Thread/ThreadStart classes when I'm initiating the thread).
1
1296
by: Flack | last post by:
Hey guys, Here is the scenario: I have the main form open and a background thread is running. The background thread sometimes needs access to the main forms graphics object and gets it by calling Graphics g = CreateGraphics(). Now, I close my main form while the background thread is running and when the background thread gets to the CreateGraphics() line, it throws an
15
1744
by: Dan Holmes | last post by:
In one of the other threads it was mentioned that using return values from methods to indicated success/failure of the method should be replaced with throwing exceptions. Which would mean code like: List l = object.Find(...); if (l == null) ... //nothing returned would be replaced with: try{
5
2226
by: Simon Tamman | last post by:
I have an object named DisasterRecovery. The Ctor of this object is this: private DisasterRecovery() { Application.ThreadException+= new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); }
0
8811
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8703
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8467
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8589
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7302
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4145
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.