0% found this document useful (0 votes)
14 views8 pages

Async Task or Async Void 1685395446

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Async Task or Async Void 1685395446

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

“Async Task”

Or
“Async Void”

Which one is correct ?

Farshad Fahimi

1
Async Task or Async Void Farshad Fahimi

In general, we use asynchronous in c# with


three following forms:

1) async Task TestMethod() {}

In this form of async calls, our method can be awaited


but does not return any values.

2) async Task<Person> TestMethod() {}

In this form of async calls, our method can be awaited


and also returns a value of type the Person.

2
Async Task or Async Void Farshad Fahimi

3) async void TestMethod() {}

In this form of async calls, which is allows for fire and


forget methods, our async method cannot be awaited.

The “await” keyword is used in an async method to


inform the compiler that the method can have a
suspension and resumption point.

3
Async Task or Async Void Farshad Fahimi

Async void methods exist for the single purpose of


being used as an event handler. More specifically, it
has been introduced to support UI elements event
handlers, nothing else.
An async method with a void return type is a "fire and
forget” method best reserved for event handlers
because there’s no way to wait for the method’s
execution to complete and respond accordingly.
There’s also no way to catch exceptions thrown from
the method.

Having an async void method that is not an event


handler could mean your program works sometimes
and not others because of timing issues. Instead, async
methods should return Task.

4
Async Task or Async Void Farshad Fahimi

Here is an example of "Async Void" and why you


should not use it in some situations, except those
times, and you want to fire and forget something.

5
Async Task or Async Void Farshad Fahimi

Here is an example of "Async Task" and why you


should not use it in some situations, except those
times, and you want to fire and forget something.

6
Async Task or Async Void Farshad Fahimi

Be aware of the consequences of using “Async void”


even if you wrapped it inside a try-catch block with the
intent of handling the exception thrown inside the
method. You be never noticed, and that is because the
exception thrown inside the Method will never be
caught.

7
TheEnd();
If you want to learn more,

Follow

Farshad Fahimi

You might also like