Task swallows exception

In the method below, when an exception is thrown in the TRY block, it is swallowed. How can I get this to throw an exception so that it is written to enter the catch block? The journalist works great. Thanks!

public static bool MonitorQueueEmptyTask(string queueName, CancellationTokenSource tokenSource)
{
    try
    {
        Task<bool> task = Task.Factory.StartNew<bool>(() =>
        {
            while (!QueueManager.IsQueueEmpty(queueName))
            {
                if (tokenSource.IsCancellationRequested)
                {                            
                    break;
                }

                Thread.Sleep(5000);
                throw new Exception("Throwing an error!"); //THIS THROW IS SWALLOWED -- NO LOG WRITTEN ON CATCH
            };

            return true;

        }, tokenSource.Token);
    }
    catch (Exception ex)
    {   
        WriteExceptionToLog(ex.Stack); //it not that this method doesn't work. it works fine.

        return false;
    }

    return true;
}
+4
source share
3 answers

If you want to shoot and forget, you can attach a sequel using ContinueWith. The current try-catchone will not help you, since the exception is encapsulated internally Task. If it is "fire and forget", you can register an exception:

public static Task MonitorQueueEmptyTask(
                         string queueName, CancellationTokenSource tokenSource)
{
    return Task.Factory.StartNew<bool>(() =>
    {
        while (!QueueManager.IsQueueEmpty(queueName))
        {
            if (tokenSource.IsCancellationRequested)
            {                            
                break;
            }

            Thread.Sleep(5000);
            throw new Exception("Throwing an error!");
        };
    }, tokenSource.Token, TaskCreationOptions.LongRunning).ContinueWith(faultedTask =>
    {
        WriteExceptionToLog(faultedTask.Exception); 
    }, TaskContinuationOptions.OnlyOnFaulted); 
}

, , , . , - , TaskScheduler.UnobservedTaskException ThrowUnobservedTaskExceptions enabled="true" . ContinueWith, "" task.Exception.

+6

; , , try/catch, .

, , , , . , TaskScheduler.UnobservedTaskException, .

+2

I also had a problem with this, and I really didn't like the whole idea of ​​App.config, so it might provide a different solution to prevent exceptions from disappearing :)

Save the exception, then throw it after the completion of Task.Run, for example.

private async void Function() {
    Exception save_exception = null;

    await Task.Run(() => {
        try {
            // Do Stuff
        } catch (Exception ex) {
            save_exception = ex;
        }
    }).ContinueWith(new Action<Task>(task => {
        if (save_exception != null)
            throw save_exception;

        // Do Stuff 
    }));
}
0
source

All Articles