Why is async void bad and how do I await a Task in an object constructor in C#?

Share this & earn $10
Brian Lagunas
Published at : 28 Oct 2020
4534 views
290
2

In this video, I answer the question "Why is async void bad and how do I await a Task in an object constructor?".

Async void is generally considered bad for 3 reasons:
1. You can’t wait for its completion (fire and forget)
2. Any unhandled exceptions will terminate your process (can't be caught)
3. Difficult to test (see #1 and #2)

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

However, let's be honest, there are many areas of our code where an async void will be required. The scenario that immediately come to mind is in the constructor of an object. For example, maybe you want to load data async when your object is first created. You want to load your data async, and let the object creation process continue without blocking any threads. This is normally done with what's called a "fire and forget" approach. Other scenarios may include the Execute method of an ICommand, or within an event handler.

Your first instinct may be to wrap these async/await calls into an "async void" method, and then just call that method in your constructor, command, or event handler. But, this is not recommended.

Luckily for use, we can use the power of a C# extension method to provide support for not only handling the completion of a Task in an async void scenario, but also handle any exceptions that may occur and provide better unit testing support.

Check out my new Pluralsight course "Introduction to Prism for WPF":
https://pluralsight.pxf.io/bE3rB

Sponsor Me:
https://github.com/sponsors/brianlagunas

Follow Me:
Twitter: https://twitter.com/brianlagunas
Twitch: https://www.twitch.tv/brianlagunas
Blog: http://brianlagunas.com
GitHub: https://github.com/brianlagunas
brian lagunasasync void c#async void try catch

HOW TO KNIT A SCARF - Hayfield Scarf | TeoMakes

HOW TO KNIT A SCARF - Hayfield Scarf | TeoMakes

Shelling Out for 100 Years

Shelling Out for 100 Years

Timro Maan (Dibya Subba) Cover By The Error Nepal

Timro Maan (Dibya Subba) Cover By The Error Nepal

Outing short vedio clips

Outing short vedio clips

MONA LISA MV 🎨💓 The popular girl's secret 🤫 Frenemies Jason and Amanda

MONA LISA MV 🎨💓 The popular girl's secret 🤫 Frenemies Jason and Amanda

ثالثه اعدادي ترم اول(مواقف الوحده الخامسه) كيفيه استخدام furthermore/in addition to+تدريب عليها

ثالثه اعدادي ترم اول(مواقف الوحده الخامسه) كيفيه استخدام furthermore/in addition to+تدريب عليها

Britney Spears - Sometimes (Official Video)

Britney Spears - Sometimes (Official Video)

U S  is staring down a 'substantial third wave' of coronavirus cases

U S is staring down a 'substantial third wave' of coronavirus cases

SpaceX Demo-1 Mannequin Is Named After 'Alien' Character

SpaceX Demo-1 Mannequin Is Named After 'Alien' Character

Stop Smoking - Why is it so hard? - Mayo Clinic

Stop Smoking - Why is it so hard? - Mayo Clinic

MERUS RESURRECTED! Granolah The Survivor Finds OG73! Dragon Ball Super Manga Chapter 67 Review

MERUS RESURRECTED! Granolah The Survivor Finds OG73! Dragon Ball Super Manga Chapter 67 Review

oil boiler replacement 2 zones repipes with storage tank

oil boiler replacement 2 zones repipes with storage tank

Want You Bad - The Offspring (Cover by Wasteland Paradise)

Want You Bad - The Offspring (Cover by Wasteland Paradise)

Mirzapur 2 की story, cast, release date, trailer reaction सब जानें । Pankaj Tripathi । Amazon Prime

Mirzapur 2 की story, cast, release date, trailer reaction सब जानें । Pankaj Tripathi । Amazon Prime

100 Last-Minute DIY Halloween Costume Ideas | CloeCouture

100 Last-Minute DIY Halloween Costume Ideas | CloeCouture

3 Hours of the Best of Fitz

3 Hours of the Best of Fitz

Tokyo Ghoul OP - Unravel [Piano/Animenz arr]

Tokyo Ghoul OP - Unravel [Piano/Animenz arr]

Quick and Easy Way to Find the Remainder of a Polynomial - Use the Remainder Theorem!

Quick and Easy Way to Find the Remainder of a Polynomial - Use the Remainder Theorem!

Metallica - The Thing That Should Not Be (Remixed and Remastered)

Metallica - The Thing That Should Not Be (Remixed and Remastered)

DO NOT WANT

DO NOT WANT

What is STROLLING? What does STROLLING mean? STROLLING meaning, definition & explanation

What is STROLLING? What does STROLLING mean? STROLLING meaning, definition & explanation

Foo Fighters - The Sky Is A Neighborhood (Live from the BRITs 2018)

Foo Fighters - The Sky Is A Neighborhood (Live from the BRITs 2018)

Trump Says He’s Opposed To Any Rule Changes For Next Debate With Biden | NBC News NOW

Trump Says He’s Opposed To Any Rule Changes For Next Debate With Biden | NBC News NOW

Norm MacDonald gambling stories // apologizes for saying show enables Artie's habits - 09/25/2008

Norm MacDonald gambling stories // apologizes for saying show enables Artie's habits - 09/25/2008

NO ONE LIKES KAR98 | PUBG MOBILE

NO ONE LIKES KAR98 | PUBG MOBILE

Far Better by Desperation Band

Far Better by Desperation Band

TREATED LIKE A BABY EP1

TREATED LIKE A BABY EP1

Visual Merchandising display using power point

Visual Merchandising display using power point

TOP TEN: Things I Find Attractive Regardless of Gender (feat. Mae Martin)

TOP TEN: Things I Find Attractive Regardless of Gender (feat. Mae Martin)

14 ตุลา: นักศึกษา การต่อสู้ และบทเรียน 47 ปีที่ไม่เคยเปลี่ยน | On This Day EP.1

14 ตุลา: นักศึกษา การต่อสู้ และบทเรียน 47 ปีที่ไม่เคยเปลี่ยน | On This Day EP.1

Martin University and Ivy Tech Community College Announcement

Martin University and Ivy Tech Community College Announcement

anders - Problems ft. Emerson

anders - Problems ft. Emerson

Comparative Advantage

Comparative Advantage

TOP 5 in FNCS WARMUP Finals | advise fn

TOP 5 in FNCS WARMUP Finals | advise fn

Perhaps, Perhaps, Perhaps (Quizas, Quizas, Quizas)

Perhaps, Perhaps, Perhaps (Quizas, Quizas, Quizas)

НАУЧИТЬСЯ СТАНТИТЬ ЗА ПАРУ ЧАСОВ, РЕАЛЬНО?

НАУЧИТЬСЯ СТАНТИТЬ ЗА ПАРУ ЧАСОВ, РЕАЛЬНО?

СЛАВА КПСС - SMOKE MOM’S PACES (ПРЕМЬЕРА ТРЕКА)

СЛАВА КПСС - SMOKE MOM’S PACES (ПРЕМЬЕРА ТРЕКА)

5 Things You Should Be Grateful For Today!

5 Things You Should Be Grateful For Today!

Why the secret to success is setting the right goals | John Doerr

Why the secret to success is setting the right goals | John Doerr

PROMPT Shoulder Dystocia Training

PROMPT Shoulder Dystocia Training

Fooling Around by Usher

Fooling Around by Usher

Difference Between Islamic and Conventional Banking

Difference Between Islamic and Conventional Banking

I Need Divorce ! 🙏 | Arranged Marriage Sathish | Men's Judicial Court ⚖️ | Celebrate Diwali #WithMe

I Need Divorce ! 🙏 | Arranged Marriage Sathish | Men's Judicial Court ⚖️ | Celebrate Diwali #WithMe

Basically Aboleths

Basically Aboleths

Photographers on Another Level! Satisfying 😍 Amazing photos Creative ideas! How are filming going

Photographers on Another Level! Satisfying 😍 Amazing photos Creative ideas! How are filming going

Rihanna - Pour It Up (Explicit)

Rihanna - Pour It Up (Explicit)

NEW EDUCATION POLICY 2020 | Curtailing Dropout Rates | Higher Education For UGC NET STET HSSC

NEW EDUCATION POLICY 2020 | Curtailing Dropout Rates | Higher Education For UGC NET STET HSSC

What do you think is the effect of such a huge amount flowing out on the Saudi economy?

What do you think is the effect of such a huge amount flowing out on the Saudi economy?

Simply Red - You've Got It (Official Video)

Simply Red - You've Got It (Official Video)