debugging async C# in visual studio; breaking on exceptions as expectedShould I add the Visual Studio .suo and .user files to source control?Visual Studio: How to break on handled exceptions?How to run Visual Studio post-build events for debug build onlyDebugging with command-line parameters in Visual StudioUsing Git with Visual Studio.gitignore for Visual Studio Projects and SolutionsDifference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?Writing to output window of Visual Studio?Can you force Visual Studio to always run as an Administrator in Windows 8?Visual Studio debugging/loading very slow

Are pressure-treated posts that have been submerged for a few days ruined?

Nominativ or Akkusativ

What does 'made on' mean here?

Emotional immaturity of comic-book version of superhero Shazam

Shutter speed -vs- effective image stabilisation

Can there be a single technologically advanced nation, in a continent full of non-technologically advanced nations?

Wrong answer from DSolve when solving a differential equation

What are the differences between credential stuffing and password spraying?

Uniform boundedness of the number of number fields having fixed discriminant

Why do people keep telling me that I am a bad photographer?

Will 700 more planes a day fly because of the Heathrow expansion?

29er Road Tire?

The number of days until the end of the month

How can I support myself financially as a 17 year old with a loan?

Frequency of specific viral sequence in .BAM or .fastq

How long would it take for people to notice a mass disappearance?

As a Bard multi-classing into Warlock, what spells do I get?

Would glacier 'trees' be plausible?

What does this wavy downward arrow preceding a piano chord mean?

Has a commercial or military jet bi-plane ever been manufactured?

Why did the Apollo 13 crew extend the LM landing gear?

Should I decline this job offer that requires relocating to an area with high cost of living?

Introducing Gladys, an intrepid globetrotter

How to use dependency injection and avoid temporal coupling?



debugging async C# in visual studio; breaking on exceptions as expected


Should I add the Visual Studio .suo and .user files to source control?Visual Studio: How to break on handled exceptions?How to run Visual Studio post-build events for debug build onlyDebugging with command-line parameters in Visual StudioUsing Git with Visual Studio.gitignore for Visual Studio Projects and SolutionsDifference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?Writing to output window of Visual Studio?Can you force Visual Studio to always run as an Administrator in Windows 8?Visual Studio debugging/loading very slow






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm struggling to figure out how to use visual studio to debug async code sanely, since it's not breaking where I want it to. For example, in this code:



using System;
using System.Threading.Tasks;

namespace TestNS
class Program
static void Main(string[] args)
Foo().Wait(); // sadly, it breaks here


static async Task Foo()
var foo = 42;
if (foo == 42)
throw new Exception(); // want it to break here






How can I get Visual Studio to automatically break where the exception is thrown and not at the top of my program? Or equivalently, without restarting the process, can I jump to that context and see the values of those locals?



I understand the root problem is that the exceptions are technically being handled by the behind the scenes async code, so VS doesn't see them as being unhandled. Surely no one else likes this behavior though, and there's a way to tell VS that exceptions that bubble up to an async call aren't really caught... I've tried turning "just my code", "break when this exception is thrown", etc., on and off, but nothing helps.



I am not looking for a solution that includes editing my code or manually adding breakpoints. Similarly, handing certain exceptions in special ways is also not a real solution. Not all the exceptions I want to break on are from my own code; often it will come from a missing key in a dictionary, or something like that.
Unexpected exceptions happen all the time when developing code, and I want to see that program state easily without manually placing breakpoints and/or try/catch code, rerunning the program, manually advancing the program until I happen to get to the function. And, that's all under the assumption I can even get it to trigger again, when I don't know anything about why it happened in the first place. And then do that for every exception that ever might occur during development.



On top of all that, if you're looking at the AggregateException that does come back, there isn't even a nice way to figure out where that exception comes from. You've got to "view details", then expand the exception, expand the inner exception, hover over the stack trace, remember the file and line number, close the details, go to the right place manually, and now put manual breakpoints and go debug manually. Why can't the system use this stack trace to do the right thing?



I'm putting all these details in because I have read 20 other SO posts about similar topics. They don't put all these details in, and people seem to go off happily, so I'm confused what I'm doing wrong. None of this happens when developing non-async code. Are all of the steps I'm doing above necessary? What is the best practice to make writing async code as pleasant as writing non-async code in terms of examining exception context?










share|improve this question






















  • did you try ticking checkbox Exception Settings --> Common Language Runtime? in visual studio?

    – sateesh
    Mar 22 at 23:12







  • 2





    static async Task Main(string[] args), and await your method call instead of using Wait()

    – Bradley Uffner
    Mar 22 at 23:15











  • @BradleyUffner after doing that, the behavior is actually worse. The application breaks, but there is no code at all to show

    – Chucky Ellison
    Mar 22 at 23:26











  • @ChuckyEllison see my answer, you most probably doesn't have configured your project to the latest c# standard, which supports async main (7.1)

    – Christian Gollhardt
    Mar 23 at 0:02

















0















I'm struggling to figure out how to use visual studio to debug async code sanely, since it's not breaking where I want it to. For example, in this code:



using System;
using System.Threading.Tasks;

namespace TestNS
class Program
static void Main(string[] args)
Foo().Wait(); // sadly, it breaks here


static async Task Foo()
var foo = 42;
if (foo == 42)
throw new Exception(); // want it to break here






How can I get Visual Studio to automatically break where the exception is thrown and not at the top of my program? Or equivalently, without restarting the process, can I jump to that context and see the values of those locals?



I understand the root problem is that the exceptions are technically being handled by the behind the scenes async code, so VS doesn't see them as being unhandled. Surely no one else likes this behavior though, and there's a way to tell VS that exceptions that bubble up to an async call aren't really caught... I've tried turning "just my code", "break when this exception is thrown", etc., on and off, but nothing helps.



I am not looking for a solution that includes editing my code or manually adding breakpoints. Similarly, handing certain exceptions in special ways is also not a real solution. Not all the exceptions I want to break on are from my own code; often it will come from a missing key in a dictionary, or something like that.
Unexpected exceptions happen all the time when developing code, and I want to see that program state easily without manually placing breakpoints and/or try/catch code, rerunning the program, manually advancing the program until I happen to get to the function. And, that's all under the assumption I can even get it to trigger again, when I don't know anything about why it happened in the first place. And then do that for every exception that ever might occur during development.



On top of all that, if you're looking at the AggregateException that does come back, there isn't even a nice way to figure out where that exception comes from. You've got to "view details", then expand the exception, expand the inner exception, hover over the stack trace, remember the file and line number, close the details, go to the right place manually, and now put manual breakpoints and go debug manually. Why can't the system use this stack trace to do the right thing?



I'm putting all these details in because I have read 20 other SO posts about similar topics. They don't put all these details in, and people seem to go off happily, so I'm confused what I'm doing wrong. None of this happens when developing non-async code. Are all of the steps I'm doing above necessary? What is the best practice to make writing async code as pleasant as writing non-async code in terms of examining exception context?










share|improve this question






















  • did you try ticking checkbox Exception Settings --> Common Language Runtime? in visual studio?

    – sateesh
    Mar 22 at 23:12







  • 2





    static async Task Main(string[] args), and await your method call instead of using Wait()

    – Bradley Uffner
    Mar 22 at 23:15











  • @BradleyUffner after doing that, the behavior is actually worse. The application breaks, but there is no code at all to show

    – Chucky Ellison
    Mar 22 at 23:26











  • @ChuckyEllison see my answer, you most probably doesn't have configured your project to the latest c# standard, which supports async main (7.1)

    – Christian Gollhardt
    Mar 23 at 0:02













0












0








0








I'm struggling to figure out how to use visual studio to debug async code sanely, since it's not breaking where I want it to. For example, in this code:



using System;
using System.Threading.Tasks;

namespace TestNS
class Program
static void Main(string[] args)
Foo().Wait(); // sadly, it breaks here


static async Task Foo()
var foo = 42;
if (foo == 42)
throw new Exception(); // want it to break here






How can I get Visual Studio to automatically break where the exception is thrown and not at the top of my program? Or equivalently, without restarting the process, can I jump to that context and see the values of those locals?



I understand the root problem is that the exceptions are technically being handled by the behind the scenes async code, so VS doesn't see them as being unhandled. Surely no one else likes this behavior though, and there's a way to tell VS that exceptions that bubble up to an async call aren't really caught... I've tried turning "just my code", "break when this exception is thrown", etc., on and off, but nothing helps.



I am not looking for a solution that includes editing my code or manually adding breakpoints. Similarly, handing certain exceptions in special ways is also not a real solution. Not all the exceptions I want to break on are from my own code; often it will come from a missing key in a dictionary, or something like that.
Unexpected exceptions happen all the time when developing code, and I want to see that program state easily without manually placing breakpoints and/or try/catch code, rerunning the program, manually advancing the program until I happen to get to the function. And, that's all under the assumption I can even get it to trigger again, when I don't know anything about why it happened in the first place. And then do that for every exception that ever might occur during development.



On top of all that, if you're looking at the AggregateException that does come back, there isn't even a nice way to figure out where that exception comes from. You've got to "view details", then expand the exception, expand the inner exception, hover over the stack trace, remember the file and line number, close the details, go to the right place manually, and now put manual breakpoints and go debug manually. Why can't the system use this stack trace to do the right thing?



I'm putting all these details in because I have read 20 other SO posts about similar topics. They don't put all these details in, and people seem to go off happily, so I'm confused what I'm doing wrong. None of this happens when developing non-async code. Are all of the steps I'm doing above necessary? What is the best practice to make writing async code as pleasant as writing non-async code in terms of examining exception context?










share|improve this question














I'm struggling to figure out how to use visual studio to debug async code sanely, since it's not breaking where I want it to. For example, in this code:



using System;
using System.Threading.Tasks;

namespace TestNS
class Program
static void Main(string[] args)
Foo().Wait(); // sadly, it breaks here


static async Task Foo()
var foo = 42;
if (foo == 42)
throw new Exception(); // want it to break here






How can I get Visual Studio to automatically break where the exception is thrown and not at the top of my program? Or equivalently, without restarting the process, can I jump to that context and see the values of those locals?



I understand the root problem is that the exceptions are technically being handled by the behind the scenes async code, so VS doesn't see them as being unhandled. Surely no one else likes this behavior though, and there's a way to tell VS that exceptions that bubble up to an async call aren't really caught... I've tried turning "just my code", "break when this exception is thrown", etc., on and off, but nothing helps.



I am not looking for a solution that includes editing my code or manually adding breakpoints. Similarly, handing certain exceptions in special ways is also not a real solution. Not all the exceptions I want to break on are from my own code; often it will come from a missing key in a dictionary, or something like that.
Unexpected exceptions happen all the time when developing code, and I want to see that program state easily without manually placing breakpoints and/or try/catch code, rerunning the program, manually advancing the program until I happen to get to the function. And, that's all under the assumption I can even get it to trigger again, when I don't know anything about why it happened in the first place. And then do that for every exception that ever might occur during development.



On top of all that, if you're looking at the AggregateException that does come back, there isn't even a nice way to figure out where that exception comes from. You've got to "view details", then expand the exception, expand the inner exception, hover over the stack trace, remember the file and line number, close the details, go to the right place manually, and now put manual breakpoints and go debug manually. Why can't the system use this stack trace to do the right thing?



I'm putting all these details in because I have read 20 other SO posts about similar topics. They don't put all these details in, and people seem to go off happily, so I'm confused what I'm doing wrong. None of this happens when developing non-async code. Are all of the steps I'm doing above necessary? What is the best practice to make writing async code as pleasant as writing non-async code in terms of examining exception context?







c# visual-studio debugging async-await






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 23:09









Chucky EllisonChucky Ellison

12627




12627












  • did you try ticking checkbox Exception Settings --> Common Language Runtime? in visual studio?

    – sateesh
    Mar 22 at 23:12







  • 2





    static async Task Main(string[] args), and await your method call instead of using Wait()

    – Bradley Uffner
    Mar 22 at 23:15











  • @BradleyUffner after doing that, the behavior is actually worse. The application breaks, but there is no code at all to show

    – Chucky Ellison
    Mar 22 at 23:26











  • @ChuckyEllison see my answer, you most probably doesn't have configured your project to the latest c# standard, which supports async main (7.1)

    – Christian Gollhardt
    Mar 23 at 0:02

















  • did you try ticking checkbox Exception Settings --> Common Language Runtime? in visual studio?

    – sateesh
    Mar 22 at 23:12







  • 2





    static async Task Main(string[] args), and await your method call instead of using Wait()

    – Bradley Uffner
    Mar 22 at 23:15











  • @BradleyUffner after doing that, the behavior is actually worse. The application breaks, but there is no code at all to show

    – Chucky Ellison
    Mar 22 at 23:26











  • @ChuckyEllison see my answer, you most probably doesn't have configured your project to the latest c# standard, which supports async main (7.1)

    – Christian Gollhardt
    Mar 23 at 0:02
















did you try ticking checkbox Exception Settings --> Common Language Runtime? in visual studio?

– sateesh
Mar 22 at 23:12






did you try ticking checkbox Exception Settings --> Common Language Runtime? in visual studio?

– sateesh
Mar 22 at 23:12





2




2





static async Task Main(string[] args), and await your method call instead of using Wait()

– Bradley Uffner
Mar 22 at 23:15





static async Task Main(string[] args), and await your method call instead of using Wait()

– Bradley Uffner
Mar 22 at 23:15













@BradleyUffner after doing that, the behavior is actually worse. The application breaks, but there is no code at all to show

– Chucky Ellison
Mar 22 at 23:26





@BradleyUffner after doing that, the behavior is actually worse. The application breaks, but there is no code at all to show

– Chucky Ellison
Mar 22 at 23:26













@ChuckyEllison see my answer, you most probably doesn't have configured your project to the latest c# standard, which supports async main (7.1)

– Christian Gollhardt
Mar 23 at 0:02





@ChuckyEllison see my answer, you most probably doesn't have configured your project to the latest c# standard, which supports async main (7.1)

– Christian Gollhardt
Mar 23 at 0:02












2 Answers
2






active

oldest

votes


















2














you need to activate Common Language Runtime exception using CTRL + ALT + E as in the picture below .



enter image description here






share|improve this answer























  • I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

    – Chucky Ellison
    Mar 22 at 23:28


















0














You need to enable Common Language Runtime exceptions as @sayah already answered.



That said, you should use async all the way up:



static async Task Main(string[] args) 
await Foo();



This will show you the exceptions, where they occour.



Stephen Cleary wrote a good article on the reasons why you want to use async to top.



Take a look at this example:



internal class Program

//static void Main(string[] args)
//
// try
//
// Foo().Wait();
//
// catch (FooException)
//
// Console.WriteLine("Yep, its a Foo Exception");
//
// catch (AggregateException)
//

// Console.WriteLine("Damn it, we got an Aggregate");
//

// Console.ReadKey();
//

static async Task Main(string[] args)

try

await Foo();

catch (FooException)

Console.WriteLine("Yep, its a Foo Exception");

catch (AggregateException)


Console.WriteLine("Damn it, we got an Aggregate");


Console.ReadKey();



class FooException : Exception



static async Task<int> Foo()

await Task.Delay(100);
var foo = 42;
if (foo == 42)
throw new FooException(); // want it to break here


return 43;




If you exchange the commented Main(), you will see, that you get an AggregateException in the non async method, while you get an FooException in the async method.




Note: If this doesn't work for you, you need to set the language level in project's advanced build settings to C# 7.1 or later, as explained here.



  • Right click your project, and click Properties

Build



  • Go to build settings and click advanced, to set the language version to C# 7.1 or later

Advanced






share|improve this answer

























  • I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

    – Chucky Ellison
    Mar 23 at 0:11











  • Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

    – Christian Gollhardt
    Mar 23 at 0:53











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55308905%2fdebugging-async-c-sharp-in-visual-studio-breaking-on-exceptions-as-expected%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














you need to activate Common Language Runtime exception using CTRL + ALT + E as in the picture below .



enter image description here






share|improve this answer























  • I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

    – Chucky Ellison
    Mar 22 at 23:28















2














you need to activate Common Language Runtime exception using CTRL + ALT + E as in the picture below .



enter image description here






share|improve this answer























  • I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

    – Chucky Ellison
    Mar 22 at 23:28













2












2








2







you need to activate Common Language Runtime exception using CTRL + ALT + E as in the picture below .



enter image description here






share|improve this answer













you need to activate Common Language Runtime exception using CTRL + ALT + E as in the picture below .



enter image description here







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 22 at 23:19









sayah imadsayah imad

38229




38229












  • I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

    – Chucky Ellison
    Mar 22 at 23:28

















  • I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

    – Chucky Ellison
    Mar 22 at 23:28
















I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

– Chucky Ellison
Mar 22 at 23:28





I only had some of them selected. Selecting all of them seems to be what I want. Hopefully I don't run into a situation where I'm debugging code that throws those kinds of exceptions in normal operation, but this is waaaay better than what I was doing before. Thanks!

– Chucky Ellison
Mar 22 at 23:28













0














You need to enable Common Language Runtime exceptions as @sayah already answered.



That said, you should use async all the way up:



static async Task Main(string[] args) 
await Foo();



This will show you the exceptions, where they occour.



Stephen Cleary wrote a good article on the reasons why you want to use async to top.



Take a look at this example:



internal class Program

//static void Main(string[] args)
//
// try
//
// Foo().Wait();
//
// catch (FooException)
//
// Console.WriteLine("Yep, its a Foo Exception");
//
// catch (AggregateException)
//

// Console.WriteLine("Damn it, we got an Aggregate");
//

// Console.ReadKey();
//

static async Task Main(string[] args)

try

await Foo();

catch (FooException)

Console.WriteLine("Yep, its a Foo Exception");

catch (AggregateException)


Console.WriteLine("Damn it, we got an Aggregate");


Console.ReadKey();



class FooException : Exception



static async Task<int> Foo()

await Task.Delay(100);
var foo = 42;
if (foo == 42)
throw new FooException(); // want it to break here


return 43;




If you exchange the commented Main(), you will see, that you get an AggregateException in the non async method, while you get an FooException in the async method.




Note: If this doesn't work for you, you need to set the language level in project's advanced build settings to C# 7.1 or later, as explained here.



  • Right click your project, and click Properties

Build



  • Go to build settings and click advanced, to set the language version to C# 7.1 or later

Advanced






share|improve this answer

























  • I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

    – Chucky Ellison
    Mar 23 at 0:11











  • Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

    – Christian Gollhardt
    Mar 23 at 0:53















0














You need to enable Common Language Runtime exceptions as @sayah already answered.



That said, you should use async all the way up:



static async Task Main(string[] args) 
await Foo();



This will show you the exceptions, where they occour.



Stephen Cleary wrote a good article on the reasons why you want to use async to top.



Take a look at this example:



internal class Program

//static void Main(string[] args)
//
// try
//
// Foo().Wait();
//
// catch (FooException)
//
// Console.WriteLine("Yep, its a Foo Exception");
//
// catch (AggregateException)
//

// Console.WriteLine("Damn it, we got an Aggregate");
//

// Console.ReadKey();
//

static async Task Main(string[] args)

try

await Foo();

catch (FooException)

Console.WriteLine("Yep, its a Foo Exception");

catch (AggregateException)


Console.WriteLine("Damn it, we got an Aggregate");


Console.ReadKey();



class FooException : Exception



static async Task<int> Foo()

await Task.Delay(100);
var foo = 42;
if (foo == 42)
throw new FooException(); // want it to break here


return 43;




If you exchange the commented Main(), you will see, that you get an AggregateException in the non async method, while you get an FooException in the async method.




Note: If this doesn't work for you, you need to set the language level in project's advanced build settings to C# 7.1 or later, as explained here.



  • Right click your project, and click Properties

Build



  • Go to build settings and click advanced, to set the language version to C# 7.1 or later

Advanced






share|improve this answer

























  • I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

    – Chucky Ellison
    Mar 23 at 0:11











  • Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

    – Christian Gollhardt
    Mar 23 at 0:53













0












0








0







You need to enable Common Language Runtime exceptions as @sayah already answered.



That said, you should use async all the way up:



static async Task Main(string[] args) 
await Foo();



This will show you the exceptions, where they occour.



Stephen Cleary wrote a good article on the reasons why you want to use async to top.



Take a look at this example:



internal class Program

//static void Main(string[] args)
//
// try
//
// Foo().Wait();
//
// catch (FooException)
//
// Console.WriteLine("Yep, its a Foo Exception");
//
// catch (AggregateException)
//

// Console.WriteLine("Damn it, we got an Aggregate");
//

// Console.ReadKey();
//

static async Task Main(string[] args)

try

await Foo();

catch (FooException)

Console.WriteLine("Yep, its a Foo Exception");

catch (AggregateException)


Console.WriteLine("Damn it, we got an Aggregate");


Console.ReadKey();



class FooException : Exception



static async Task<int> Foo()

await Task.Delay(100);
var foo = 42;
if (foo == 42)
throw new FooException(); // want it to break here


return 43;




If you exchange the commented Main(), you will see, that you get an AggregateException in the non async method, while you get an FooException in the async method.




Note: If this doesn't work for you, you need to set the language level in project's advanced build settings to C# 7.1 or later, as explained here.



  • Right click your project, and click Properties

Build



  • Go to build settings and click advanced, to set the language version to C# 7.1 or later

Advanced






share|improve this answer















You need to enable Common Language Runtime exceptions as @sayah already answered.



That said, you should use async all the way up:



static async Task Main(string[] args) 
await Foo();



This will show you the exceptions, where they occour.



Stephen Cleary wrote a good article on the reasons why you want to use async to top.



Take a look at this example:



internal class Program

//static void Main(string[] args)
//
// try
//
// Foo().Wait();
//
// catch (FooException)
//
// Console.WriteLine("Yep, its a Foo Exception");
//
// catch (AggregateException)
//

// Console.WriteLine("Damn it, we got an Aggregate");
//

// Console.ReadKey();
//

static async Task Main(string[] args)

try

await Foo();

catch (FooException)

Console.WriteLine("Yep, its a Foo Exception");

catch (AggregateException)


Console.WriteLine("Damn it, we got an Aggregate");


Console.ReadKey();



class FooException : Exception



static async Task<int> Foo()

await Task.Delay(100);
var foo = 42;
if (foo == 42)
throw new FooException(); // want it to break here


return 43;




If you exchange the commented Main(), you will see, that you get an AggregateException in the non async method, while you get an FooException in the async method.




Note: If this doesn't work for you, you need to set the language level in project's advanced build settings to C# 7.1 or later, as explained here.



  • Right click your project, and click Properties

Build



  • Go to build settings and click advanced, to set the language version to C# 7.1 or later

Advanced







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 23 at 0:51

























answered Mar 22 at 23:49









Christian GollhardtChristian Gollhardt

10.4k124880




10.4k124880












  • I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

    – Chucky Ellison
    Mar 23 at 0:11











  • Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

    – Christian Gollhardt
    Mar 23 at 0:53

















  • I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

    – Chucky Ellison
    Mar 23 at 0:11











  • Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

    – Christian Gollhardt
    Mar 23 at 0:53
















I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

– Chucky Ellison
Mar 23 at 0:11





I tried this as mentioned above, and the behavior is actually worse. The application breaks, but there is no code at all to show in the debugger. Try unchecking the "Common Language Runtime" in "break when thrown" and you should see the same behavior. The problem is "break when thrown" not async all the way up.

– Chucky Ellison
Mar 23 at 0:11













Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

– Christian Gollhardt
Mar 23 at 0:53





Yeah just tested, and you are right. Not sure about why... If I recall correct, it worked the last time I tried, but it was a more complex application. Anyway, you should do it the async, see my example above @ChuckyEllison

– Christian Gollhardt
Mar 23 at 0:53

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55308905%2fdebugging-async-c-sharp-in-visual-studio-breaking-on-exceptions-as-expected%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해