Archive for November, 2008

Catching Thread Exceptions in C#

I have a Winforms app where I am performing asynchronous functions. I am using the delegate model and have threadsafe calls for updating my UI. My worker threads happen in an instance of another class, not the class that is the form.

I had the impression that the global Application.ThreadException event handler would catch exceptions that happened off on my working threads. This does not seem to be the case. The following code (as a console app) shows my problem and won’t catch the exception. The program executes as if nothing bad happened.

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using System.Threading;
 
namespace BadThreadException
{
    class Program
    {
        delegate void WorkerDelegate(int input);
 
        static void Main(string[] args)
        {
            Application.ThreadException += new ThreadExceptionEventHandler(App_ThreadException);
 
            Worker mult = new Worker();
 
            AsyncCallback callback = new AsyncCallback(Finished);
 
            WorkerDelegate threadedWork = new WorkerDelegate(mult.DoSomethingImpressive);
 
            threadedWork.BeginInvoke(9, callback, null);
 
            Console.ReadKey();
        }
 
        static void Finished(IAsyncResult result)
        {
            Console.WriteLine("Done");
        }
 
        static void App_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Console.WriteLine("Got an error");
        }
    }
 
    class Worker
    {
        public void DoSomethingImpressive(int input)
        {
            throw new Exception("Ouch");
        }
    }
 
}

Well, I definitely need a solution to the problem, since exceptions definitely can happen off in my worker class. After some research, it turns out that you must call the EndInvode method on the delegate for the exception to bubble up. In my case, I wasn’t calling it because there was no return type. Now I understand why people frequently mention it is a best practice to always call EndInvoke, even if you don’t care about the return value (Doh!). The correct callback looks like this:

        static void Finished(IAsyncResult result)
        {
            AsyncResult ar = (AsyncResult)result;
            WorkerDelegate d = (WorkerDelegate)ar.AsyncDelegate;
 
            try
            {
                d.EndInvoke(ar);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Got an error on the callback");
            }
 
            Console.WriteLine("Done");
        }

I still haven’t discovered how/when the Application.ThreadException event handler gets called.

Posted on:
Posted in Winforms | Comments Off on Catching Thread Exceptions in C#

Quick ADO.Net Tip

If you need to stop a datareader in the middle, instead of at the end, you have to call cancel on the command object. Calling the Close() method will result in a timeout exception.

using (SqlCommand cmd = new SqlCommand(sql, conn))
{
          XmlReader reader = cmd.ExecuteXmlReader();
          reader.Read();

while (!reader.EOF)
{
            if (this.Cancel)
            {
                cmd.Cancel();
                reader.Close():
                break;
            }
            holder = reader.ReadOuterXml();
}

}

Posted on:
Posted in .Net 2.0 | Comments Off on Quick ADO.Net Tip

Getting Started with WCF and REST

Now that WCF has support for REST in .Net 3.5, it’s time to get learning….


WCF REST Starter Kit


A Guide to Designing and Building RESTful Web Services with WCF 3.5

A bunch of screencasts by Aaron Skonnard

WCF and REST from the PDC

Dan RigsbyREST support in WCF

Posted on:
Posted in .Net 3.5, WCF | Comments Off on Getting Started with WCF and REST