tuespetre
tuespetre

Reputation: 1887

Why is this code resulting in an unhandled exception?

The following code seems as though it should swallow any type of exception in the try block, but the IIS worker process periodically dies and restarts because of an unhandled exception (marked with a comment.)

try
{
    while (true)
    {
        DispatcherTask task = null;

        lock (sync)
        {
            task = this.getTask();

            if (task == null)
            {
                Monitor.Wait(sync);
                continue;
            }
        }

        lock (task)
        {
            task.Result = task.Task.DynamicInvoke(task.Params);
            // ^ Delegate.DynamicInvoke(object[]) throws a TargetInvocationException

            Monitor.PulseAll(task);
        }
    }
}
catch (Exception e)
{
}

UPDATE:

Definition of DispatcherTask:

private class DispatcherTask
{
    public Delegate Task;

    public object[] Params;

    public object Result;
}

Upvotes: 1

Views: 424

Answers (2)

tuespetre
tuespetre

Reputation: 1887

In .NET 4 and up, AccessViolationException will bypass catch blocks by default. Catching of such exceptions can be enabled in web.config, but should not be, as they typically result from errors in unmanaged code and signal that the application state is corrupted.

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76953

You cannot catch the exceptions of another thread, at least not in this way. Catch your exception inside the newly opened thread and you will be fine.

Upvotes: 2

Related Questions