SlideShare a Scribd company logo
Async Debugging - A Practical
Guide to survive !
@MircoVanini
www.proxsoft.it
Mirco Vanini
Microsoft MVP Windows Developer
• Sync To Async Code
• Async state machine
• Async logical call stack (chain of continuations)
• Debug
• Parallel Stacks for Tasks and Theads
• Tasks Window
• Threads Window
• Parallel Watch
• Rethrown Exceptions
• Snapshot on Exception (IntelliTrace -> Historical Debugger)
• Async Guidance
• Q&A
Agenda
Start plain and simple
public double GetTotalOderedByCustomer(string customer)
{
double total = 0;
foreach (var order in GetOrdersByCustomer(customer))
{
var details = order.GetOrderDetails();
total += details.Sum(d => d.Quantity * d.UnitPrice);
}
return total;
}
Everythings is frozen and we
are doomed !
…How about adding some
async/await ?
Compiler generated code
public async Task<double> GetTotalOderedByCustomerAsync(string customer)
{
double total = 0;
foreach (var order in await GetOrdersByCustomerAsync(customer))
{
var details = await order.GetOrderDetailsAsync();
total += details.Sum(d => d.Quantity * d.UnitPrice);
}
return total;
}
[AsyncStateMachine(typeof(<GetTotalOderedByCustomerAsync>d__0))]
[DebuggerStepThrough]
public Task<double> GetTotalOderedByCustomerAsync(string customer)
{
<GetTotalOderedByCustomerAsync>d__0 stateMachine = new
<GetTotalOderedByCustomerAsync>d__0();
stateMachine.<>t__builder = AsyncTaskMethodBuilder<double>.Create();
stateMachine.<>4__this = this;
stateMachine.customer = customer;
stateMachine.<>1__state = -1;
stateMachine.<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
Compiler generated code
public async Task<double>
GetTotalOderedByCustomerAsync(string customer)
{
double total = 0;
foreach (var order in await
GetOrdersByCustomerAsync(customer))
{
var details = await order.GetOrderDetailsAsync();
total += details.Sum(d => d.Quantity *
d.UnitPrice);
}
return total;
}
[CompilerGenerated]
private sealed class <GetTotalOderedByCustomerAsync>d__0 : IAsyncStateMachine
{
public int <>1__state;
public AsyncTaskMethodBuilder<double> <>t__builder;
// local variables !
public string customer;
public DataService <>4__this;
private double <total>5__1;
...
// awaiters !
private TaskAwaiter<IEnumerable<Order>> <>u__1;
private TaskAwaiter<IEnumerable<OrderDetail>> <>u__2;
private void MoveNext()
{
int num = <>1__state;
double result;
try
{
TaskAwaiter<IEnumerable<Order>> awaiter;
if (num != 0)
{
if (num == 1)
{
goto IL_00c4;
}
<total>5__1 = 0.0;
awaiter = <>4__this.GetOrdersByCustomerAsync(customer).GetAwaiter();
Without Await
public Task<double> GetTotalOderedByCustomerWithoutAwait(string customer)
{
ConcurrentBag<double> totals = new ConcurrentBag<double>();
Task<IEnumerable<Order>> fetchOrders = Task.Run(() => GetOrdersByCustomer(customer));
Task matchOrders = fetchOrders.ContinueWith(t =>
{
List<Task> matchTasks = new();
foreach (var order in t.Result)
{
Task<IEnumerable<OrderDetail>> detailTask = Task.Run(() => order.GetOrderDetails());
Task matchDetail = detailTask.ContinueWith(t1 =>
{
totals.Add(t1.Result.Sum(d => d.Quantity * d.UnitPrice));
}, TaskContinuationOptions.AttachedToParent);
matchTasks.Add(matchDetail);
}
return Task.WhenAll(matchTasks);
});
return matchOrders.ContinueWith(_ => totals.Sum(p => p));
}
Async code – call stack
Debug > Windows > Call stack | Debug > Windows > Threads > main thread)
Async code – call stack
Debug > Windows > Parallel Stacks > Threads
Async logical call stack
The first thing used while debugging are «call stacks»
Call stack show caller -> callee relation !
We also need call stack fro async code – such as «async call stacks»
So how do we debug this ?
Async vs sync stacks
SYNC stacks ASYNC stacks
Code is currently running on a thread Code may not be running anywhere or
scheduled to run in the future
Hence – Physical stacks Virtual or logical stacks. Not tied to a single
(or any) thread.
Locals are allocated on stack memory Local are stashed in “state machines”
(internal compiler generated helper
structures)
Async call stacks
Task #1
GetOrderByCustomerAsync()
m_continuation
public async Task<double> GetTotalOderedByCustomerAsync(string customer)
{
double total = 0;
foreach (var order in await GetOrdersByCustomerAsync(customer))
{
var details = await order.GetOrderDetailsAsync();
total += details.Sum(d => d.Quantity * d.UnitPrice);
}
return total;
}
Task #2
GetOrderDetailsAsync()
m_continuation
Here the await keyword adds the next line of GetTotalOrderedByCutomerAsync
as a continuation to GetOrdersByCustomerAsync.
The Task of GetOderDetailsAsync store a reference to the next line of
GetTotalOrderedByCutomerAsync to invoke when done.
Async call stacks
Task #1
GetOrderByCustomerAsync()
m_continuation
Task #2
GetOrderDetailsAsync()
m_continuation
The debugger walks through this chain of references – to get a chain of
continuations
Async Logical Stacks
GetOrderDetailsAsync
GetOrderByCustomerAsync
The chian of continuations is what we call async call stack
Async call stacks
Task #1
GetOrderByCustomerAsync()
m_continuation
Task #2
GetOrderDetailsAsync()
m_continuation
Async stack are a continuation stack
This may be quite different from the stack or context of where the task
was created – that is, the creation stack
Task #N
...
m_continuation
Creation Stack vs Continuation Stack
Note that TakeABreak is not part of the async call stack
Async Task
> Task.Delay(…)
DoSomething(…)
public Task TakeABreak()
{
return Task.Delay(1000);
}
public async Task DoSomething()
{
foreach (var order in orders)
{
Task pause = TakeABreak():
details = await order.GetOrderDetails();
await pause;
}
}
??? TakeABreak(…) ???
Creation Stack vs Continuation Stack
Sync call stack are also really just continuation stack: the creation (call) and
continuation are the same
In async, control goes to whoever awaits (or waits) the current async code,
which may be different from the scope or method in which it was called.
Keep that in mind while async debugging – especially while using
TaskCompletitionSource<T> [used for APM (Asynchronous Programming
Model) or EAP (Event-Based Asynchronous Pattern)].
Async call stacks
public async Task DoSomething()
{
List<Task> tasks = new List<Task>();
foreach (var order in orders)
{
tasks.Add(order.GetOrderDetailsAsync());
}
await Task.WhenAll(tasks);
}
Task #1
GetOrderDetailsAsync()
m_continuation
Task #2
GetOrderDetailsAsync()
m_continuation
Task #2
GetOrderDetailsAsync()
m_continuation
Task #1
DoSomething()
m_continuation
DEMO
Parallel Stacks for Tasks and Theads
Tasks Window – Threads Window
Rethrown Exceptions / Snapshot on Exception
• Async void
• Prefer Task.FromResult over Task.Run for pre-computed or trivially computed data
• Avoid using Task.Run for long running work that blocks the thread
• Avoid using Task.Result and Task.Wait
• Prefer await over ContinueWith
• Always create TaskCompletionSource<T> with
TaskCreationOptions.RunContinuationsAsynchronously
• Always dispose CancellationTokenSource(s) used for timeouts
• Always flow CancellationToken(s) to APIs that take a CancellationToken
• Cancelling uncancellable operations
• Always call FlushAsync on StreamWriter(s) or Stream(s) before calling Dispose
• Prefer async/await over directly returning Task
• ConfigureAwait
Async Code Tips
The first debugging step is writing good code !
AsyncGuidance
Question Time
myContactInfo:
{
”e-mail”:“mirco.vanini@proxsoft.it”,
“web”: “www.proxsoft.it”,
“twitter”: “@MircoVanini”
}
Mirco Vanini
Microsoft MVP Windows Developer
Thanks to
Ad

More Related Content

What's hot (20)

Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.
CocoaHeads France
 
RBuilder and ByteSurgeon
RBuilder and ByteSurgeonRBuilder and ByteSurgeon
RBuilder and ByteSurgeon
Marcus Denker
 
Clang tidy
Clang tidyClang tidy
Clang tidy
Yury Yafimachau
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
Sergey Platonov
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
Pavel Albitsky
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
Stratio
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
zznate
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
yayaria
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
Rami Sayar
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
Lukasz Dobrzanski
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
Andrey Karpov
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
vorfeed chen
 
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Emery Berger
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
Saúl Ibarra Corretgé
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Codemotion
 
FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!
Vincent Claes
 
Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.
CocoaHeads France
 
RBuilder and ByteSurgeon
RBuilder and ByteSurgeonRBuilder and ByteSurgeon
RBuilder and ByteSurgeon
Marcus Denker
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
Pavel Albitsky
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
Stratio
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
zznate
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
yayaria
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
Rami Sayar
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
Andrey Karpov
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
vorfeed chen
 
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Emery Berger
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Codemotion
 
FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!
Vincent Claes
 

Similar to Async Debugging - A Practical Guide to survive ! (20)

Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
mcwilson1
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
What the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupWhat the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startup
Gerrit Grunwald
 
Why async matters
Why async mattersWhy async matters
Why async matters
timbc
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
PeckaDesign.cz
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 
Spark streaming with kafka
Spark streaming with kafkaSpark streaming with kafka
Spark streaming with kafka
Dori Waldman
 
Spark stream - Kafka
Spark stream - Kafka Spark stream - Kafka
Spark stream - Kafka
Dori Waldman
 
Async fun
Async funAsync fun
Async fun
💡 Tomasz Kogut
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
Stefan Marr
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
Sync with async
Sync with  asyncSync with  async
Sync with async
prabathsl
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
Dmitri Nesteruk
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
Pratik Khasnabis
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
Particular Software
 
Seastar @ NYCC++UG
Seastar @ NYCC++UGSeastar @ NYCC++UG
Seastar @ NYCC++UG
Avi Kivity
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
Rainer Stropek
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
mcwilson1
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
What the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupWhat the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startup
Gerrit Grunwald
 
Why async matters
Why async mattersWhy async matters
Why async matters
timbc
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
PeckaDesign.cz
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 
Spark streaming with kafka
Spark streaming with kafkaSpark streaming with kafka
Spark streaming with kafka
Dori Waldman
 
Spark stream - Kafka
Spark stream - Kafka Spark stream - Kafka
Spark stream - Kafka
Dori Waldman
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
Stefan Marr
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
Sync with async
Sync with  asyncSync with  async
Sync with async
prabathsl
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
Dmitri Nesteruk
 
Seastar @ NYCC++UG
Seastar @ NYCC++UGSeastar @ NYCC++UG
Seastar @ NYCC++UG
Avi Kivity
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
Rainer Stropek
 
Ad

More from Mirco Vanini (20)

.NET 7 Performance Improvements_10_03_2023.pdf
.NET 7 Performance Improvements_10_03_2023.pdf.NET 7 Performance Improvements_10_03_2023.pdf
.NET 7 Performance Improvements_10_03_2023.pdf
Mirco Vanini
 
Debugging a .NET program after crash (Post-mortem debugging)
Debugging a .NET program after crash (Post-mortem debugging)Debugging a .NET program after crash (Post-mortem debugging)
Debugging a .NET program after crash (Post-mortem debugging)
Mirco Vanini
 
Connect a chips to Azure
Connect a chips to AzureConnect a chips to Azure
Connect a chips to Azure
Mirco Vanini
 
Connect a chips to Azure
Connect a chips to AzureConnect a chips to Azure
Connect a chips to Azure
Mirco Vanini
 
How to modernise WPF and Windows Forms applications with Windows Apps SDK
How to modernise WPF and Windows Forms applications with Windows Apps SDKHow to modernise WPF and Windows Forms applications with Windows Apps SDK
How to modernise WPF and Windows Forms applications with Windows Apps SDK
Mirco Vanini
 
C# on a CHIPs
C# on a CHIPsC# on a CHIPs
C# on a CHIPs
Mirco Vanini
 
.NET Conf 2021 - Hot Topics Desktop Development
.NET Conf 2021 - Hot Topics Desktop Development.NET Conf 2021 - Hot Topics Desktop Development
.NET Conf 2021 - Hot Topics Desktop Development
Mirco Vanini
 
IoT support for .NET (Core/5/6)
IoT support for .NET (Core/5/6)IoT support for .NET (Core/5/6)
IoT support for .NET (Core/5/6)
Mirco Vanini
 
IoT support for .NET Core
IoT support for .NET CoreIoT support for .NET Core
IoT support for .NET Core
Mirco Vanini
 
IoT support for .NET Core - IoT Saturday 2020
IoT support for .NET Core - IoT Saturday 2020IoT support for .NET Core - IoT Saturday 2020
IoT support for .NET Core - IoT Saturday 2020
Mirco Vanini
 
.NET Conf 2020 - Hot Topics Desktop Development
.NET Conf 2020 - Hot Topics Desktop Development.NET Conf 2020 - Hot Topics Desktop Development
.NET Conf 2020 - Hot Topics Desktop Development
Mirco Vanini
 
Are you ready for Microsoft Azure Sphere?
Are you ready for Microsoft Azure Sphere?Are you ready for Microsoft Azure Sphere?
Are you ready for Microsoft Azure Sphere?
Mirco Vanini
 
IoT Day 2019 Naples - Microsoft Azure Shpere
IoT Day 2019 Naples - Microsoft Azure ShpereIoT Day 2019 Naples - Microsoft Azure Shpere
IoT Day 2019 Naples - Microsoft Azure Shpere
Mirco Vanini
 
Debugging with VS2019
Debugging with VS2019Debugging with VS2019
Debugging with VS2019
Mirco Vanini
 
Azure Sphere
Azure SphereAzure Sphere
Azure Sphere
Mirco Vanini
 
Optimising code using Span<T>
Optimising code using Span<T>Optimising code using Span<T>
Optimising code using Span<T>
Mirco Vanini
 
Azure Sphere
Azure SphereAzure Sphere
Azure Sphere
Mirco Vanini
 
Xe OneDay - Modernizing Enterprise Apps
Xe OneDay - Modernizing Enterprise AppsXe OneDay - Modernizing Enterprise Apps
Xe OneDay - Modernizing Enterprise Apps
Mirco Vanini
 
Azure Sphere - GAB 2019
Azure Sphere - GAB 2019Azure Sphere - GAB 2019
Azure Sphere - GAB 2019
Mirco Vanini
 
IoT Day - Introducing Azure Sphere
IoT Day -  Introducing Azure SphereIoT Day -  Introducing Azure Sphere
IoT Day - Introducing Azure Sphere
Mirco Vanini
 
.NET 7 Performance Improvements_10_03_2023.pdf
.NET 7 Performance Improvements_10_03_2023.pdf.NET 7 Performance Improvements_10_03_2023.pdf
.NET 7 Performance Improvements_10_03_2023.pdf
Mirco Vanini
 
Debugging a .NET program after crash (Post-mortem debugging)
Debugging a .NET program after crash (Post-mortem debugging)Debugging a .NET program after crash (Post-mortem debugging)
Debugging a .NET program after crash (Post-mortem debugging)
Mirco Vanini
 
Connect a chips to Azure
Connect a chips to AzureConnect a chips to Azure
Connect a chips to Azure
Mirco Vanini
 
Connect a chips to Azure
Connect a chips to AzureConnect a chips to Azure
Connect a chips to Azure
Mirco Vanini
 
How to modernise WPF and Windows Forms applications with Windows Apps SDK
How to modernise WPF and Windows Forms applications with Windows Apps SDKHow to modernise WPF and Windows Forms applications with Windows Apps SDK
How to modernise WPF and Windows Forms applications with Windows Apps SDK
Mirco Vanini
 
.NET Conf 2021 - Hot Topics Desktop Development
.NET Conf 2021 - Hot Topics Desktop Development.NET Conf 2021 - Hot Topics Desktop Development
.NET Conf 2021 - Hot Topics Desktop Development
Mirco Vanini
 
IoT support for .NET (Core/5/6)
IoT support for .NET (Core/5/6)IoT support for .NET (Core/5/6)
IoT support for .NET (Core/5/6)
Mirco Vanini
 
IoT support for .NET Core
IoT support for .NET CoreIoT support for .NET Core
IoT support for .NET Core
Mirco Vanini
 
IoT support for .NET Core - IoT Saturday 2020
IoT support for .NET Core - IoT Saturday 2020IoT support for .NET Core - IoT Saturday 2020
IoT support for .NET Core - IoT Saturday 2020
Mirco Vanini
 
.NET Conf 2020 - Hot Topics Desktop Development
.NET Conf 2020 - Hot Topics Desktop Development.NET Conf 2020 - Hot Topics Desktop Development
.NET Conf 2020 - Hot Topics Desktop Development
Mirco Vanini
 
Are you ready for Microsoft Azure Sphere?
Are you ready for Microsoft Azure Sphere?Are you ready for Microsoft Azure Sphere?
Are you ready for Microsoft Azure Sphere?
Mirco Vanini
 
IoT Day 2019 Naples - Microsoft Azure Shpere
IoT Day 2019 Naples - Microsoft Azure ShpereIoT Day 2019 Naples - Microsoft Azure Shpere
IoT Day 2019 Naples - Microsoft Azure Shpere
Mirco Vanini
 
Debugging with VS2019
Debugging with VS2019Debugging with VS2019
Debugging with VS2019
Mirco Vanini
 
Optimising code using Span<T>
Optimising code using Span<T>Optimising code using Span<T>
Optimising code using Span<T>
Mirco Vanini
 
Xe OneDay - Modernizing Enterprise Apps
Xe OneDay - Modernizing Enterprise AppsXe OneDay - Modernizing Enterprise Apps
Xe OneDay - Modernizing Enterprise Apps
Mirco Vanini
 
Azure Sphere - GAB 2019
Azure Sphere - GAB 2019Azure Sphere - GAB 2019
Azure Sphere - GAB 2019
Mirco Vanini
 
IoT Day - Introducing Azure Sphere
IoT Day -  Introducing Azure SphereIoT Day -  Introducing Azure Sphere
IoT Day - Introducing Azure Sphere
Mirco Vanini
 
Ad

Recently uploaded (20)

Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
User interface and User experience Modernization.pptx
User interface and User experience  Modernization.pptxUser interface and User experience  Modernization.pptx
User interface and User experience Modernization.pptx
MustafaAlshekly1
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
jamesmartin143256
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Comprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety ReportingComprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety Reporting
EHA Soft Solutions
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Let's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured ContainersLet's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured Containers
Gene Gotimer
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
User interface and User experience Modernization.pptx
User interface and User experience  Modernization.pptxUser interface and User experience  Modernization.pptx
User interface and User experience Modernization.pptx
MustafaAlshekly1
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
jamesmartin143256
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Comprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety ReportingComprehensive Incident Management System for Enhanced Safety Reporting
Comprehensive Incident Management System for Enhanced Safety Reporting
EHA Soft Solutions
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Let's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured ContainersLet's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured Containers
Gene Gotimer
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 

Async Debugging - A Practical Guide to survive !

  • 1. Async Debugging - A Practical Guide to survive ! @MircoVanini www.proxsoft.it Mirco Vanini Microsoft MVP Windows Developer
  • 2. • Sync To Async Code • Async state machine • Async logical call stack (chain of continuations) • Debug • Parallel Stacks for Tasks and Theads • Tasks Window • Threads Window • Parallel Watch • Rethrown Exceptions • Snapshot on Exception (IntelliTrace -> Historical Debugger) • Async Guidance • Q&A Agenda
  • 3. Start plain and simple public double GetTotalOderedByCustomer(string customer) { double total = 0; foreach (var order in GetOrdersByCustomer(customer)) { var details = order.GetOrderDetails(); total += details.Sum(d => d.Quantity * d.UnitPrice); } return total; } Everythings is frozen and we are doomed ! …How about adding some async/await ?
  • 4. Compiler generated code public async Task<double> GetTotalOderedByCustomerAsync(string customer) { double total = 0; foreach (var order in await GetOrdersByCustomerAsync(customer)) { var details = await order.GetOrderDetailsAsync(); total += details.Sum(d => d.Quantity * d.UnitPrice); } return total; } [AsyncStateMachine(typeof(<GetTotalOderedByCustomerAsync>d__0))] [DebuggerStepThrough] public Task<double> GetTotalOderedByCustomerAsync(string customer) { <GetTotalOderedByCustomerAsync>d__0 stateMachine = new <GetTotalOderedByCustomerAsync>d__0(); stateMachine.<>t__builder = AsyncTaskMethodBuilder<double>.Create(); stateMachine.<>4__this = this; stateMachine.customer = customer; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start(ref stateMachine); return stateMachine.<>t__builder.Task; }
  • 5. Compiler generated code public async Task<double> GetTotalOderedByCustomerAsync(string customer) { double total = 0; foreach (var order in await GetOrdersByCustomerAsync(customer)) { var details = await order.GetOrderDetailsAsync(); total += details.Sum(d => d.Quantity * d.UnitPrice); } return total; } [CompilerGenerated] private sealed class <GetTotalOderedByCustomerAsync>d__0 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder<double> <>t__builder; // local variables ! public string customer; public DataService <>4__this; private double <total>5__1; ... // awaiters ! private TaskAwaiter<IEnumerable<Order>> <>u__1; private TaskAwaiter<IEnumerable<OrderDetail>> <>u__2; private void MoveNext() { int num = <>1__state; double result; try { TaskAwaiter<IEnumerable<Order>> awaiter; if (num != 0) { if (num == 1) { goto IL_00c4; } <total>5__1 = 0.0; awaiter = <>4__this.GetOrdersByCustomerAsync(customer).GetAwaiter();
  • 6. Without Await public Task<double> GetTotalOderedByCustomerWithoutAwait(string customer) { ConcurrentBag<double> totals = new ConcurrentBag<double>(); Task<IEnumerable<Order>> fetchOrders = Task.Run(() => GetOrdersByCustomer(customer)); Task matchOrders = fetchOrders.ContinueWith(t => { List<Task> matchTasks = new(); foreach (var order in t.Result) { Task<IEnumerable<OrderDetail>> detailTask = Task.Run(() => order.GetOrderDetails()); Task matchDetail = detailTask.ContinueWith(t1 => { totals.Add(t1.Result.Sum(d => d.Quantity * d.UnitPrice)); }, TaskContinuationOptions.AttachedToParent); matchTasks.Add(matchDetail); } return Task.WhenAll(matchTasks); }); return matchOrders.ContinueWith(_ => totals.Sum(p => p)); }
  • 7. Async code – call stack Debug > Windows > Call stack | Debug > Windows > Threads > main thread)
  • 8. Async code – call stack Debug > Windows > Parallel Stacks > Threads
  • 9. Async logical call stack The first thing used while debugging are «call stacks» Call stack show caller -> callee relation ! We also need call stack fro async code – such as «async call stacks» So how do we debug this ?
  • 10. Async vs sync stacks SYNC stacks ASYNC stacks Code is currently running on a thread Code may not be running anywhere or scheduled to run in the future Hence – Physical stacks Virtual or logical stacks. Not tied to a single (or any) thread. Locals are allocated on stack memory Local are stashed in “state machines” (internal compiler generated helper structures)
  • 11. Async call stacks Task #1 GetOrderByCustomerAsync() m_continuation public async Task<double> GetTotalOderedByCustomerAsync(string customer) { double total = 0; foreach (var order in await GetOrdersByCustomerAsync(customer)) { var details = await order.GetOrderDetailsAsync(); total += details.Sum(d => d.Quantity * d.UnitPrice); } return total; } Task #2 GetOrderDetailsAsync() m_continuation Here the await keyword adds the next line of GetTotalOrderedByCutomerAsync as a continuation to GetOrdersByCustomerAsync. The Task of GetOderDetailsAsync store a reference to the next line of GetTotalOrderedByCutomerAsync to invoke when done.
  • 12. Async call stacks Task #1 GetOrderByCustomerAsync() m_continuation Task #2 GetOrderDetailsAsync() m_continuation The debugger walks through this chain of references – to get a chain of continuations Async Logical Stacks GetOrderDetailsAsync GetOrderByCustomerAsync The chian of continuations is what we call async call stack
  • 13. Async call stacks Task #1 GetOrderByCustomerAsync() m_continuation Task #2 GetOrderDetailsAsync() m_continuation Async stack are a continuation stack This may be quite different from the stack or context of where the task was created – that is, the creation stack Task #N ... m_continuation
  • 14. Creation Stack vs Continuation Stack Note that TakeABreak is not part of the async call stack Async Task > Task.Delay(…) DoSomething(…) public Task TakeABreak() { return Task.Delay(1000); } public async Task DoSomething() { foreach (var order in orders) { Task pause = TakeABreak(): details = await order.GetOrderDetails(); await pause; } } ??? TakeABreak(…) ???
  • 15. Creation Stack vs Continuation Stack Sync call stack are also really just continuation stack: the creation (call) and continuation are the same In async, control goes to whoever awaits (or waits) the current async code, which may be different from the scope or method in which it was called. Keep that in mind while async debugging – especially while using TaskCompletitionSource<T> [used for APM (Asynchronous Programming Model) or EAP (Event-Based Asynchronous Pattern)].
  • 16. Async call stacks public async Task DoSomething() { List<Task> tasks = new List<Task>(); foreach (var order in orders) { tasks.Add(order.GetOrderDetailsAsync()); } await Task.WhenAll(tasks); } Task #1 GetOrderDetailsAsync() m_continuation Task #2 GetOrderDetailsAsync() m_continuation Task #2 GetOrderDetailsAsync() m_continuation Task #1 DoSomething() m_continuation
  • 17. DEMO
  • 18. Parallel Stacks for Tasks and Theads
  • 19. Tasks Window – Threads Window
  • 20. Rethrown Exceptions / Snapshot on Exception
  • 21. • Async void • Prefer Task.FromResult over Task.Run for pre-computed or trivially computed data • Avoid using Task.Run for long running work that blocks the thread • Avoid using Task.Result and Task.Wait • Prefer await over ContinueWith • Always create TaskCompletionSource<T> with TaskCreationOptions.RunContinuationsAsynchronously • Always dispose CancellationTokenSource(s) used for timeouts • Always flow CancellationToken(s) to APIs that take a CancellationToken • Cancelling uncancellable operations • Always call FlushAsync on StreamWriter(s) or Stream(s) before calling Dispose • Prefer async/await over directly returning Task • ConfigureAwait Async Code Tips The first debugging step is writing good code ! AsyncGuidance
  翻译: