Exception not fired when using TPL - c#

I have the following code which does not fire the AggregateException
Aggregate Exception is not fired and I don't understand why? Normally it should as Aggregate exception is used to catch exceptions while running code using tasks
class Program
{
static void Main(string[] args)
{
var task1 = Task.Factory.StartNew(() =>
{
Test();
}).ContinueWith((previousTask) =>
{
Test2();
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
// Handle the custom exception.
if (e is CustomException)
{
Console.WriteLine(e.Message);
}
// Rethrow any other exception.
else
{
throw;
}
}
}
}
static void Test()
{
throw new CustomException("This exception is expected!");
}
static void Test2()
{
Console.WriteLine("Test2");
}
}
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{ }
}
}

That's because you are waiting for completion of your continuation task (which runs Test2()), not for completion of task which runs Test(). First task fails with exception and then continuation task does nothing with this exception (you don't check if previousTask has failed) and completes successfully. To catch that exception you need to wait for first task or check result of it in continuation:
var task1 = Task.Factory.StartNew(() =>
{
Test();
});
var task2 = task1.ContinueWith((previousTask) =>
{
Test2();
});
or
var task1 = Task.Factory.StartNew(() =>
{
Test();
}).ContinueWith((previousTask) =>
{
if (previousTask.Exception != null) {
// do something with it
throw previousTask.Exception.GetBaseException();
}
Test2();
}); // note that task1 here is `ContinueWith` task, not first task
That's all not related of course to whether you should really do it like this or not, just to answer the question.

Related

TaskCanceledException: Cancel or timeout?

I only want to use CancellationTokenSource for timeout and cancellation handling.
How to distinguish if a TaskCanceledException occured due to a timeout or due to manual cancellation?
Here is a simplified example. In the real program I neither know if CancellationTokenSource .CancelAfter() was used nor if someone called CancellationTokenSource.Cancel()
static CancellationTokenSource cts = new CancellationTokenSource();
static void Main(string[] args)
{
Task.Run(async () =>
{
try
{
await SomeClass.DoSomething(cts.Token);
}
catch (TaskCanceledException ex)
{
//How to find out if the exception occured due to timeout or a call to cts.Cancel()
}
});
while (true)
{
Thread.Sleep(100);
if (someCondition)
cts.Cancel();
}
}
public class SomeClass
{
public static async Task DoSomething(CancellationToken ct)
{
using (var innerCts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
innerCts.CancelAfter(1000);
//Simulate some operation
await Task.Delay(10000, innerCts.Token);
}
}
}
thanks
Tom
AFAIK this is the most commonly used pattern:
Task.Run(async () =>
{
try
{
await SomeClass.DoSomething(cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
// cts cancellation occurred
}
catch (OperationCanceledException)
{
// Timeout occurred
}
});
Another idea is to change the implementation of the SomeClass.DoSomething method, assuming that you are allowed to do it, so that in case of timeout it throws a TimeoutException instead of an OperationCanceledException.
public static async Task DoSomething(CancellationToken cancellationToken)
{
using var innerCts = new CancellationTokenSource(millisecondsDelay: 1000);
using var linkedCts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken, innerCts.Token);
try
{
// Simulate some operation
await Task.Delay(10000, linkedCts.Token);
}
catch (OperationCanceledException) when (innerCts.IsCancellationRequested)
{
throw new TimeoutException();
}
}

Exception not being caught by first catch, and instead get handled by a top level catch

I have a class called SearchProbe for I'm writing unit tests. One unit test is for testing the ability of my class's main processing method (called RunSearchProbe) to be able to respond to CancellationTokens correctly. My class's main processing method executes async submethods which all throw an OperationCanceledException when a CancellationToken is cancelled. Then in my main method RunSearchProbe, I'm trying to catch this exception and respond to it.
Problem: The problem is that for some reason, OperationCanceledException is NOT being caught in the main method RunSearchProbe, and it comes all the way upto my unit test's call stack for handling, and I don't know why ?!
Here's my main class:
public class SearchProbe
{
protected async Task RunSearchProbe(CancellationToken cancellationToken) {
try
{
try
{
using (cancellationToken.Register(() => {
//some code here
}))
{
Task<bool> initTask = Initialize(cancellationToken);
await initTask;
//some code here
}
}
catch (Exception exception) when (exception.GetType().Equals(typeof(OperationCanceledException))
|| exception.InnerException.GetType().Equals(typeof(OperationCanceledException)))
{
//some code here // -------->>> (Point 1) This is where the OperationCanceledException SHOULD get caught
}
finally
{
//some code here
}
}
catch (Exception e)
{
//some code here // -------->>> (Point 2) ... Or AT LEAST get caught here
}
}
private async Task<bool> Initialize(CancellationToken cancellationToken) {
try
{
using (cancellationToken.Register(() => {
throw new OperationCanceledException();
}))
{
//some code here
return true;
}
}
catch (Exception exception)
{
//some code here
}
}
}
This is a mock inherited class:
class MockSearchProbe : SearchProbe
{
static MockSearchProbe()
{
//some code here
}
public async Task RunProbeManually()
{
try {
CancellationTokenSource cts = new CancellationTokenSource();
Task probeTask = RunSearchProbe(cts.Token);
cts.Cancel();
await probeTask;
}
catch (Exception exception) when (exception.GetType().Equals(typeof(OperationCanceledException))
|| exception.InnerException.GetType().Equals(typeof(OperationCanceledException)))
{
//do something (Point 3) ... But it actually gets caught here for some reason
}
}
}
This is the test class:
[TestClass]
public class SearchProbeTests
{
[TestMethod]
public async Task TestProbe_Cancellation()
{
MockSearchProbe probe = new MockSearchProbe();
Task result = probe.RunProbeManually();
await result;
}
}
Please see steps 1, 2 and 3 commented above to see what I mean ... Why is the catch block inside my main class's RunSearchProbe method NOT catching the OperationCanceledException ??
The documentation for CancellationToken.Regsiter states that the method:
Registers a delegate that will be called when this CancellationToken is canceled.
Based on that description, I would expect that the registration callback defined in the Initialize method should execute when cts.Cancel() is called in RunProbeManually. The exception is not instantiated or thrown until that point, which is in the scope of the try/catch block labeled "Point 3."
Here's a simplified illustration:
using System;
class MainClass {
public static void Main (string[] args) {
Action throwException = null;
try {
Console.WriteLine("Defining delegate");
throwException = () => {
Console.WriteLine("Throwing exception");
throw new Exception();
};
} catch (Exception) {
Console.WriteLine("Exception caught at point 1");
}
try {
Console.WriteLine("Invoking delegate");
throwException.Invoke();
} catch (Exception) {
Console.WriteLine ("Exception caught at point 2");
}
}
}
Output:
Defining delegate
Invoking delegate
Throwing exception
Exception caught at point 2

AggregateException Not Thrown in Task.Run()

I am trying to catch an AggregateException from a Task.Run() operation which intentionally fails, however an AggregateException is not thrown. Why?
public void EnterWaitingRoom(string val)
{
try
{
Task.Run(() => InvokeHubMethod("HubMethod",
new object[] { val }));
}
catch (AggregateException ex)
{
// This exception is not caught
throw ex;
}
}
private async Task<object> InvokeHubMethod(string method, object[] args)
{
return await Task.Run(() => _hubProxy.Invoke<object>(method,
args).Result);
}
I expect the exception to be thrown but it is not.
I also tried adding .Wait and still don't get the exception.
The request is coming from a windows UI.
Any ideas. Thanks.
This is how you enter the async/await from an EventHandler
public async void Button_Click(object sender, RoutedEventArgs args )
{
object result = await EnterWaitingRoom( "whatever" );
}
private Task<object> EnterWaitingRoom(string val)
{
return InvokeHubMethod(
"HubMethod",
new object[] { val } );
}
private Task<object> InvokeHubMethod(string method, object[] args)
{
return _hubProxy.Invoke<object>(
method,
args);
}

Passing exception from Task.Run to await properly and Debugger

This is the task, where the exception is being thrown.
public Task<SensorReading> ReadSensorsAsync(int cell)
{
return Task.Run(() => {
throw new ArgumentNullException();
...
This is the async method:
private async void TimerCallback(object state)
{
try
{
var tasksRead = Enumerable.Range(3, 35).Select(i => sensorReader.ReadSensorsAsync(i)).ToList();
await Task.WhenAll(tasksRead);
var r = tasksRead.Select(x => x.Result).ToList();
var taskRecordREsult = RecordReadingAsync(r).Result;
}
catch(Exception e)
{
// expecting to catch everything here
}
}
What I was expecting is that exception would be handled in await part of the code. However, I am getting unhandled exception in Visual Studio debugger.
Question - how to properly pass all kind of exception from Task.Run to awaitable part?
One possible solution is to extract your Task.Run lambda into a standalone method, and add the [DebuggerStepThrough] attribute to it. In theory (I haven't tested this), this will suppress the first exception in the debugger, and allow it to be caught later. It's not pretty, but it should do the trick.
try this program and see if you still get breaking..
its working for me
class Program
{
static void Main(string[] args)
{
new Program().TimerCallback();
}
public Task<string> ReadSensorsAsync(string cell)
{
return Task.Run(() =>
{
if(cell == null) throw new ArgumentNullException();
return cell;
});
}
public Task<string> RecordReadingAsync(IEnumerable<string> cell)
{
return Task.Run(() =>
{
return string.Join(",", cell);
});
}
public async void TimerCallback()
{
try
{
var tasksRead = new string[] { "1", null, "3" }.Select(s => ReadSensorsAsync(s));
var taskRecordResult = await RecordReadingAsync(await Task.WhenAll(tasksRead));
Debugger.Log(1, "test", taskRecordResult);
}
catch (Exception e)
{
//catches here
Debugger.Log(1, "test", e.Message ?? e.ToString());
}
}
}

Try-Catch Async Exceptions

This example "fails":
static async void Main(string[] args)
{
try
{
await TaskEx.Run(() => { throw new Exception("failure"); });
}
catch (Exception)
{
throw new Exception("success");
}
}
That is, the exception with the text "failure" bubbles up.
Then I tried this workaround:
static async void Main(string[] args)
{
try
{
await SafeRun(() => { throw new Exception("failure"); });
}
catch (Exception)
{
throw new Exception("success");
}
}
static async Task SafeRun(Action action)
{
var ex = default(Exception);
await TaskEx.Run(() =>
{
try
{
action();
}
catch (Exception _)
{
ex = _;
}
});
if (ex != default(Exception))
throw ex;
}
That didn't help either.
I suppose my Async CTP refresh installation could be hosed.
Should this code work as I expect ("success" bubbles up, not "failure"), or is this not "supposed" to work that way. And if not, how would you work around it?
The behavior you are seeing is likely an edge case bug or may even be correct, if unintuitive. Normally when you invoke an async method synchronously, it wraps a task around to execute and since there is no one waiting on the task to finish, the exception never makes it to the main thread. If you were to call Main directly it would succeed, but then your runtime would see an exception of "success" on another thread.
Since main is the entrypoint of your application, it is invoked synchronously and likely as the entrypoint doesn't trigger the Task wrapping behavior, so that await isn't run properly and the TaskEx.Run throws on its own thread, which shows up in the runtime as an exception being thrown on another thread.
If you were to run main as an async method, i.e. returning a Task (since an async that returns void can only really be called via await) and blocking on it from your synchronous main context, you would get the appropriate behavior as the below test illustrates:
static async Task Main() {
try {
await TaskEx.Run(() => { throw new Exception("failure"); });
} catch(Exception) {
throw new Exception("success");
}
}
static async Task Main2() {
await Main();
}
[Test]
public void CallViaAwait() {
var t = Main2();
try {
t.Wait();
Assert.Fail("didn't throw");
} catch(AggregateException e) {
Assert.AreEqual("success",e.InnerException.Message);
}
}
[Test]
public void CallDirectly() {
var t = Main();
try {
t.Wait();
Assert.Fail("didn't throw");
} catch(AggregateException e) {
Assert.AreEqual("success", e.InnerException.Message);
}
}
I.e. the Task faults with an AggregateException which contains the success exception as it's inner exception.

Categories