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.