I am new to tasks and I hope you can help me out with this.
Here is code:
Task tast = null;
try
{
tast = new Task(() =>
{
...
});
tast.Start();
if (tast != null)
{
tast.Wait();
if (tast.Exception != null)
{
// catch exception here
}
}
}
catch (Exception err)
{
// not here?
}
The exception is being caught inside catch statement but not inside task.Exception != null.
Why is this happening? Task should be on own thread.
I would rather like to make the task know about exception and then ask if exception != null.
How can I make that work?
I am sorry in case this is a duplicate. Just let me know in comments and I will remove this question.
You're calling Task.Wait()
- which will throw an exception if the task is faulted. If you don't call Task.Wait()
, you won't get the exception in your thread... but of course you won't spot when it's finished, either. There are various ways you could wait until it's finished (such as attaching a continuation task and waiting until that completes) but the simplest approach is just to call Task.Wait()
with a catch block:
try
{
task.Wait();
}
catch (AggregateException)
{
// We'll handle this later.
}
See more on this question at Stackoverflow