Exception in task not breaking immediately - c#

Some pseudo code to illustrate my problem:
public async Task DoSomethingAsync()
{
try
{
var task1 = DoThisAsync(); // throws exception
var task2 = DoThatAsync();
await task1.Then(t => Handle(t));
await task2.Then(t => Handle(t));
}
catch (AggregateException)
{
Console.WriteLine("Whatnow?");
}
}
And Then is defined as such:
// from https://gist.github.com/rizal-almashoor/2818038
public static Task Then(this Task task, Action<Task> next)
{
var tcs = new TaskCompletionSource<AsyncVoid>();
task.ContinueWith(t=>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception); // continuing task1 this line only gets hit
// after DoThatAsync() is completed??
else
{
try
{
next(t);
tcs.TrySetResult(default(AsyncVoid));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
So my problem is that for some reason, even though DoThisAsync() throws an exception pretty early, I don't see "whatnow" until DoThatAsync() is finished.
This is not the exact code, I tried to simplify to not waste your time. If there's nothing here that explains this behavior let me know and I will add more detail.
Edit
For the purpose of this question we can imagine DoThisAsync() and DoThatAsync() are to asynchronouse methods that basically do the following:
DoThisAsync:
Thread.Sleep(30000); // wait a short perioud of time
throw new Exception(); // and throw an exception
DoThatAsnyc:
Thread.Sleep(240000); // wait a long period of time

Presumably your DoThisAsync starts a new task and the action of that task is what throws the exception--is that right?
In that case, the exception is stored within the Task. The exception will not be rethrown unless you call a trigger method like .Wait, or .Result. When you await the task returned from Then, it is causing that task's exception to be rethrown.
Edit:
Based on your edits showing the DoThisAsync:
When an async marked method that returns a Task causes an exception, that exception is stored in the Task (rather than allowing it to propagate). If you were to remove the async keyword I would expect the exception to happen at the time DoThisAsync is called.
Edit:
From Stephen Toub's Async/Await FAQ: http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx:
What does the “async” keyword do when applied to a method?
When you mark a method with the “async” keyword, you’re really telling the compiler two things:
You’re telling the compiler that you want to be able to use the “await” keyword inside the method (you can use the await keyword if and only if the method or lambda it’s in is marked as async). In doing so, you’re telling the compiler to compile the method using a state machine, such that the method will be able to suspend and then resume asynchronously at await points.
You’re telling the compiler to “lift” the result of the method or any exceptions that may occur into the return type. For a method that returns Task or Task, this means that any returned value or exception that goes unhandled within the method is stored into the result task. For a method that returns void, this means that any exceptions are propagated to the caller’s context via whatever “SynchronizationContext” was current at the time of the method’s initial invocation.

Related

TaskContinuationOptions OnlyOnCancelled catches unhandled errors

I have following code to handle my TaskContinuations. I am bit confused because I have below OnlyOnFaulted block which I expect will be entered if the task throws an unhandled exception.
However, unhandled exception, handled exception that is rethrown using throw, or cancellation will land in the OnlyOnCanceled block.
GetDataAsync(id).ContinueWith((antecedant) =>
{
// do something when async method completed
}, TaskContinuationOptions.OnlyOnRanToCompletion)
.ContinueWith((antecedant) =>
{
var error = antecedant.Exception.Flatten(); //so when is this called if everything is cought by OnCancelled below?
}, TaskContinuationOptions.OnlyOnFaulted)
.ContinueWith((antecedant) =>
{
// this is fired if method throws an exception or if CancellationToken cancelled it or if unhandled exception cought
var error = "Task has been cancelled";
}, TaskContinuationOptions.OnlyOnCanceled);
I would expect that re-thrown errors and cancellations will land in the OnlyOnCanceled block whereas unhandled exception will land in the OnlyOnFaulted block
Note that I cannot just await GetDataAsync because this is called in a method called from View's c-tor. I explained that in this post NetworkStream ReadAsync and WriteAsync hang infinitelly when using CancellationTokenSource - Deadlock Caused by Task.Result (or Task.Wait)
UPDATE
Instead using code above, I am using Task.Run like below. I am decorating the lambda passed into Task.Run with async to provide "Async all the way" as recommended by Jon Goldberger at https://blog.xamarin.com/getting-started-with-async-await/
Task.Run(async() =>
{
try
{
IList<MyModel> models = await GetDataAsync(id);
foreach (var model in models)
{
MyModelsObservableCollection.Add(model);
}
} catch (OperationCancelledException oce) {}
} catch (Exception ex) {}
});
This felt a better solution since I can wrap the code inside Task.Run with try...catch block and the exception handling is behaving as I would expect.
I am definitely planning to give a try to suggestion offered by Stephen Cleary at https://msdn.microsoft.com/en-us/magazine/dn605875.aspx as it seam to be a cleaner solution.
As I said in my other answer, you should use await, and, since this is a constructor for a ViewModel, you should synchronously initialize to a "Loading..." state and asynchronously update that ViewModel to a "Display Data" state.
To answer this question directly, the problem is that ContinueWith returns a task representing the continuation, not the antecedent. To simplify the code in your question:
GetDataAsync(id)
.ContinueWith(A(), TaskContinuationOptions.OnlyOnRanToCompletion);
.ContinueWith(B(), TaskContinuationOptions.OnlyOnFaulted)
.ContinueWith(C(), TaskContinuationOptions.OnlyOnCanceled);
A() will be called if GetDataAsync(id) runs to completion. B() will be called if A() faults (note: not if GetDataAsync(id) faults). C() will be called if B() is canceled (note: not if GetDataAsync(id) is canceled).
There are a couple of other problems with your usage of ContinueWith: it's missing some flags (e.g., DenyChildAttach), and it's using the current TaskScheduler, which can cause surprising behavior. ContinueWith is an advanced, low-level method; use await instead.

Is there any other way to set Task.Status to Cancelled

Ok, so I understand how to do Task cancellations using CancellationTokenSource. it appears to me that the Task type "kind of" handles this exception automatically - it sets the Task's Status to Cancelled.
Now you still actually have to handle the OperationCancelledException. Otherwise the exception bubbles up to Application.UnhandledException. The Task itself kind of recognizes it and does some handling internally, but you still need to wrap the calling code in a try block to avoid the unhandled exception. Sometimes, this seems like unnecessary code. If the user presses cancel, then cancel the Task (obviously the task itself needs to handle it too). I don't feel like there needs to be any other code requirement. Simply check the Status property for the completion status of the task.
Is there any specific reason for this from a language design point of view? Is there any other way to set the Status property to cancelled?
You can set a Task's status to cancelled without a CancellationToken if you create it using TaskCompletionSource
var tcs = new TaskCompletionSource();
var task = tcs.Task;
tcs.SetCancelled();
Other than that you can only cancel a running Task with a CancellationToken
You only need to wrap the calling code in a try/catch block where you're asking for the result, or waiting for the task to complete - those are the situations in which the exception is thrown. The code creating the task won't throw that exception, for example.
It's not clear what the alternative would be - for example:
string x = await GetTaskReturningString();
Here we never have a variable referring to the task, so we can't explicitly check the status. We'd have to use:
var task = GetTaskReturningString();
string x = await task;
if (task.Status == TaskStatus.Canceled)
{
...
}
... which is not only less convenient, but also moves the handling of the "something happened" code into the middle of the normal success path.
Additionally, by handling cancellation with an exception, if you have several operations, you can put all the handling in one catch block instead of checking each task separately:
try
{
var x = await GetFirstTask();
var y = await GetSecondTask(x);
}
catch (OperationCanceledException e)
{
// We don't care which was canceled
}
The same argument applies for handling cancellation in one place wherever in the stack the first cancellation occurred - if you have a deep stack of async methods, cancellation in the deepest method will result in the top-most task being canceled, just like normal exception propagation.

What happens when you await a failed task

I have a theoretical question to you. What happens if I await the Result of a Task inside another task? I want to know if my current system will work afterwards.
A task gets launched and does some stuff. At some point that task might need another one in order to process data which the current task is not able to process by itself. So I use await to ensure that the current task won't continue as long as he has not the result of the helper task. But what happens if the helper fails? Will the current task remain locked?
Can I avoid this deadlock somehow (without changing the system itself - task inside task)?
A task gets launched and does some stuff. At some point that task might need another one in order to process data which the current task is not able to process by itself. So I use await to ensure that the current task won't continue as long as he has not the result of the helper task. But what happens if the helper fails? Will the current task remain locked?
The core idea behind async and await is that asynchronous code works just about the same as synchronous code.
So, if you have synchronous code like this:
void HelperMethod()
{
throw new InvalidOperationException("test");
}
void DoStuff()
{
HelperMethod();
}
then you would expect DoStuff to propagate the InvalidOperationException from the helper method. Similarly, that's what happens with asynchronous code:
async Task HelperMethodAsync()
{
throw new InvalidOperationException("test");
}
async Task DoStuffAsync()
{
await HelperMethodAsync();
}
That is, DoStuffAsync will also propagate the InvalidOperationException.
Now, it doesn't work exactly the same way, of course, since it must be asynchronous, but the general idea is that all your control flow such as try/catch, for loops, etc, all "just work" for asynchronous code very similarly to synchronous code.
What's actually going on is that when HelperMethod ends with an InvalidOperationException, the exception is caught and placed on the returned Task, and the task is completed. When the await in DoStuffAsync sees that the task has completed, it examines its exceptions and re-raises the first one (in this case, there is only one, the InvalidOperationException). And it re-raises it in a way that preserves the call stack on the exception. This in turn causes the Task returned from DoStuffAsync to be completed with that same exception.
So, under the covers async and await are doing a bit of work to ensure that you can just call other methods with await and use try/catch the same way as you would in synchronous code. But most of the time you don't have to be aware of that.
It's really easy to test. For example:
[TestMethod, ExpectedException(typeof(Exception))]
public async Task DoFaultedTaskThrowOnAwait()
{
var task = Task.Factory.StartNew(() => { throw new Exception("Error 42"); });
await task;
}
[TestMethod, ExpectedException(typeof(AggregateException))]
public void DoFaultedTaskThrowOnWait()
{
var task = Task.Factory.StartNew(() => { throw new Exception("Error 42"); });
task.Wait();
}
Both tests pass, notice that Wait throws an AggregateException, and await throws the Exception.
What happens if I await the Result of a Task inside another task?
You can only await a Task.Result if it is an awaitable (meaning it has a GetAwaiter method). This is rarely the case. I assume you mean await on an inner Task.
But what happens if the helper fails? Will the current task remain locked?
First, im not sure what you mean by "locked". The task isn't locked while you await on the inner task. Control is yielded back to the calling method until that inner task completes. If that inner task fails and you fail to properly handle that exception, you parent task will fault as well. You need to make sure you handle exceptions gracefully:
var task =
Task.Run(async () =>
{
try
{
await AsyncHelper.DoSomethingAsync();
}
catch (Exception e)
{
// Handle exception gracefully
}
});
If you await on the parent Task, you'll notice the inner exception propogating from the unhandled inner Task.
Can I avoid this deadlock somehow?
I see no reason why your code should deadlock in this specific case. Not sure why this worries you.

Will awaiting multiple tasks observe more than the first exception?

Today my colleagues and I discussed how to handle exceptions in C# 5.0 async methods correctly, and we wondered if awaiting multiple tasks at once also observes the exceptions that do not get unwrapped by the runtime.
Consider the following code snippet:
async Task ExceptionMethodAsync()
{
await Task.Yield();
throw new Exception();
}
async Task CallingMethod()
{
try
{
var a = ExceptionMethodAsync();
var b = ExceptionMethodAsync();
await Task.WhenAll(a, b);
}
catch(Exception ex)
{
// Catches the "first" exception thrown (whatever "first" means)
}
}
What happens to the second task now? Both will be in a faulted state, but is the second task's exception now observed or unobserved?
Task.WhenAll returns a task and like all tasks the Exception property holds an AggregateException that combines all exceptions.
When you await such a task only the first exception will actually be thrown.
... Whether because of child tasks that fault, or because of combinators like Task.WhenAlll, a single task may represent multiple operations, and more than one of those may fault. In such a case, and with the goal of not losing exception information (which can be important for post-mortem debugging), we want to be able to represent multiple exceptions, and thus for the wrapper type we chose AggregateException.
... Given that, and again having the choice of always throwing the first or always throwing an aggregate, for “await” we opt to always throw the first
from Task Exception Handling in .NET 4.5
It's up to you to choose if you want to handle just the first using await task; (true in most cases) or handle all using task.Exception (as in my example below), but in both cases a and b would not raise an UnobservedTaskException.
var task = Task.WhenAll(a, b);
try
{
await task;
}
catch
{
Trace.WriteLine(string.Join(", ", task.Exception.Flatten().InnerExceptions.Select(e => e.Message)));
}

Async method throws exception instantly but is swallowed when async keyword is removed

I'm getting some behaviour which I cannot understand when throwing exceptions in async methods.
The following code will throw an exception immediately when calling the ThrowNow method. If I comment that line out and throw the exception directly then the exception is swallowed and not raised in the Unobserved event handler.
public static async void ThrowNow(Exception ex){
throw ex;
}
public static async Task TestExAsync()
{
ThrowNow(new System.Exception("Testing")); // Throws exception immediately
//throw new System.Exception("Testing"); // Exception is swallowed, not raised in unobserved event
await Task.Delay(1000);
}
void Main()
{
var task = TestExAsync();
}
Something a little more confusing, if I remove the async keyword from the ThrowNow method, the exception is swallowed yet again.
I thought async methods run synchronously until reaching a blocking method. In this case, it seems that removing the async keyword is making it behave asynchronously.
I thought async methods run synchronously until reaching a blocking method.
They do, but they're still aware that they're executing within an asynchronous method.
If you throw an exception directly from an async void method, the async mechanism is aware that you'd have no way of observing that exception - it won't be thrown back to the caller, because exceptions thrown in async methods are only propagated through tasks. (The returned task becomes faulted.) It would be odd for an exception thrown before the first blocking await expression to be thrown directly, but exceptions afterwards to be handled differently.
As far as I'm aware, an exception thrown by an async void method is passed directly to the synchronization context, if there is one. (A continuation is posted to the synchronization context that just throws the exception.) In a simple console app, there isn't a synchronization context, so instead it's thrown as an unreported exception.
If you change your void method to return Task, then instead you'll just have an exception which could have been observed, but isn't (because you're not using the return value in TestExAsync).
Does that make any sense? Let me know if you'd like more clarification - it's all a bit tortuous (and I don't know how well documented it is).
EDIT: I've found a bit of documentation, in the C# 5 spec section 10.15.2:
If the return type of the async function is void, evaluation differs from the above in the following way: Because no task is returned, the function instead communicates completion and exceptions to the current thread's synchronization context. The exact definition of synchronization context is implementation-dependent, but is a representation of "where" the current thread is running. The synchronization context is notified when evaluation of a void-returning async function commences, completes successfully, or causes an uncaught exception to be thrown.
Something a little more confusing, if I remove the async keyword from the ThrowNow method, the exception is swallowed yet again.
Exceptions are not "swallowed".
In addition to what Jon Skeet said, consider this code where ThrowNow is not marked async:
static void ThrowNow(Exception ex)
{
throw ex;
}
static async Task TestExAsync()
{
ThrowNow(new System.Exception("Testing"));
await Task.Delay(1000);
}
static void Main()
{
var task = TestExAsync();
Console.WriteLine(task.Exception);
}
As you can see, exceptions are not "swallowed", they're just communicated to you in the task returned from an asynchronous method.
Obviously, that also means you cannot try catch them, unless you await the task:
static void Main()
{
AsyncMain();
}
static async void AsyncMain()
{
var task = TestExAsync();
try
{
await task;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

Categories

Resources