0

Suppose I have a TaskCompletionSource where I explicitly set its exception via SetException(Exception). Am I still required to access the Exception property of its task to avoid the

"A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread."

message?

Specific example:

try
{
    ThreadEnd();
    _disposeCompletionSource.SetResult(42);
}
catch (Exception e)
{
    Log.FatalFormat("Caught unexpected exception while shutting down thread {0}:\n{1}", _thread.Name, e);
    _disposeCompletionSource.SetException(e);
}

Do I need to Continue() the task to avoid rethrowing the exception on the finalizer thread or am I good?

Simon
  • 428
  • 5
  • 19
  • 1
    What does the fact that you're using `TaskCompletionSource` have to do with anything? It's whoever is using `_disposeCompletionSource.Task` who has to do the work, which is true regardless of where the `Task` came from (this is an implementation detail). There's nothing special about `TaskCompletionSource` in this regard. (So the short answer to your question is "yes".) – Jeroen Mostert Apr 14 '16 at 10:35
  • 1
    ...having said that, that message produced by the finalizer is a courtesy to you, the programmer, that something wasn't done properly. There's no guarantee you'll get that message under all circumstances, and not getting it doesn't mean your code is bug-free. I mention this because you seem to think avoiding the message is the goal -- the goal should be to avoid the problem that message is hinting at (unobserved exceptions, as in, nobody made a conscious choice what should happen if an exception occurred). – Jeroen Mostert Apr 14 '16 at 10:56
  • Thanks for the answer. You're right that using TaskCompletionSource is not related to the problem at all. The reason why I ask is that this code in question is related to cleanup code - the application can't really do much when this code fails, other than log that exception. – Simon Apr 14 '16 at 11:20
  • 1
    If this is cleanup code, why does the task have a result? If it has a result, someone must be observing that result (and that code will also observe the exception). If it had no result, it would be correct to log the exception and thereby consider it handled (and simply flag the task as completed). (If you're just using a result because that's how `TaskCompletionSource` rolls: then just use a dummy result in the exception handler as well.) – Jeroen Mostert Apr 14 '16 at 11:26
  • You're right, it really doesn't make sense to set the exception, I'll change it. Thanks! – Simon Apr 14 '16 at 15:08

0 Answers0