SlideShare a Scribd company logo
1 of 29
Threading model in Windows Store
apps
Mirco Vanini
Microsoft® MVP Windows Embedded
 Why threads?
 Windows threading model
 Objects and threading – Marshaling
 Agile objects
 Thread pool threads
 Using the thread pool in Windows Runtime apps
Agenda
 Service connected world
 Responsive apps
 Touch-based experience
 Many cores
Why threads?
 Kernel threads
 Separate processes
 Brokers
 Async operations
How Windows parallelizes for you
 UI objects live in a UI thread
 Main UI thread lasts as long as app
 Most other objects can be used on any thread
 We pass out work to thread pool when needed
Windows threading model
 Windows objects follow natural and familiar object rules
 You control lifetime
 You can use them on threads you take them to
 Where you create them doesn’t constrain where you use or
delete them
 One of our biggest changes relative to COM
Windows threading model
Windows threading model
App
Windows
UI
Object
Main UI Thread
Windows
Object
Threadpool
App Code App Code App Code
Windows
Object
 Three main types of object
 Thread bound – works only on the thread where it was created – most UI
 Thread flexible – works on any thread, uses locking if needed to control
simultaneous access
 Brokered – out of process
 UI runs in single threaded environment that is not reentrant
(“Application STA”)
 Callbacks can only enter if they are related to an outgoing call
 Most non-UI runs in any thread
Windows threading model
Brokered Objects
RuntimeBroker.exe
Windows
Runtime Object
IInspectable
IUnknown
App
Projection
Proxy
 User interface has special threading needs
 Don’t want OK to be pressed during OnCancel
 UI objects are deliberately and naturally serialized
 Don’t do long running work on UI thread
 Instead, offload large work to thread pool with async object
UI threads
 Objects on UI threads generally don’t need locking to protect
themselves
 UI threads are not reentrant
 UI threads can’t call each other directly
 Rejected at call time in Windows 8.1
 Use dispatcher or async object to avoid
UI threads
 No long delays allowed on UI threads
 Most classic waiting primitives are inappropriate
 Windows will terminate unresponsive apps
 Instead, use UI-safe primitives
 C#: await
 C++: create_task
 JS: promise
UI threads
 App primary UI always launched on main UI thread
 Contract UI (e.g. Share) launched on separate UI thread
 Main UI thread used for global state
 Other UI threads for documents, contracts
 Main UI thread stays alive until app dies
Main UI thread
 XAML UI objects are thread-bound
 Use dispatcher to move UI work back to relevant UI thread
 Whole XAML tree must host on a single thread
 XAML events will be delivered on the UI thread
 Async operations started on XAML threads have results
delivered back on UI thread
 DirectX situation similar
XAML environment threading
 Basic WinRT protocols are threading-agnostic
 IUnknown, IInspectable manages the object and its interfaces
 WinRT protocols allow for some objects to have special
threading requirements
 WinRT captures all these concepts with marshaling
Objects and threading
 Marshaling allows an object to be used from another thread
or process
 Most WinRT objects do not require marshaling
 Even references to out-of-process objects (proxies) are agile
in WinRT
 Objects decide how they are marshaled
 IMarshal, INoMarshal control marshaling
Marshaling
 Agile objects are objects that can work in any thread of a
process without being marshalled
 Agile objects are simple to deal with
 Most WinRT objects are agile
 Out-of-process proxies are agile
 Agile objects do not die if their original host thread dies
Agile objects
 Apartments are a COM concept that group and control
thread and object lifetimes
 Apartments exist in WinRT but have been made largely
irrelevant by agility to reduce pain
 Three types in Windows Store apps
 Application single-threaded apartment (ASTA) – UI threads
 Multithreaded apartment (MTA) – Thread pool
 Neutral threaded apartment (NTA) – Used by WinRT to help inter-
process calls
Apartments
 Where long-running work is done
 Allocated, scaled and scheduled by the operating system
 WinRT async operations automatically happen here
 Always initialized for WinRT usage when created
 Objects may be called back on any thread
Thread pool threads
 Your app can use the thread pool to accomplish work
asynchronously in parallel threads
 The thread pool offers more control than the asynchronous
programming patterns
 Submit work items, control their priority, and cancel work items
 Schedule work items using timers and periodic timers
 Set aside resources for critical work items
 Run work items in response to named events and semaphores
Using the thread pool
Submitting a work item to
the thread pool
demo
Submit a work item using a
timer
demo
Create a periodic work
item
demo
Respond to named events
and semaphores
demo
 Use the thread pool to do parallel work in your app
 Use work items to accomplish extended tasks without blocking the UI thread
 Create work items that are short-lived and independent. Work items run
asynchronously and they can be submitted to the pool in any order from the
queue
 Dispatch updates to the UI thread with the Windows.UI.Core.CoreDispatcher
 Use ThreadPoolTimer.CreateTimer instead of the Sleep function
 Use the thread pool instead of creating your own thread management system.
The thread pool runs at the OS level with advanced capability and it is already
optimized
Using the thread pool – Do’s
 Don't create periodic timers with a period value of <1 millisecond (including 0).
This will cause the work item to behave as a single-shot timer
 Don't submit periodic work items that take longer to complete than the amount of
time you specified in the period parameter
 Don't do any extensive work in the UI dispatch handler. The handler provided to
the UI core dispatcher runs in the UI thread
 Don't try to send UI updates (other than toasts and notifications) from a work item
running in a background task. Instead, use background task progress and
completion handlers
 Don't try to create work item handlers that use the async keyword
Using the thread pool – Dont's
 WinRT designed to make threading natural, simple, and
familiar
 Don’t block the UI thread
 Use async for long running operations
 Use the thread pool to accomplish work asynchronously in
parallel threads
Recap
Q&A
Contact
feedback
10
Blog http://mircovanini.blogspot.com
Email info@proxsoft.it
Web www.proxsoft.it
Twitter@MircoVanini

More Related Content

Viewers also liked

Title sequence to thrillers
Title sequence to thrillersTitle sequence to thrillers
Title sequence to thrillers
amycoker
 
mood boards
mood boardsmood boards
mood boards
amycoker
 
Автоматизация смешанного обучения на платформе SAP
Автоматизация смешанного обучения на платформе SAP Автоматизация смешанного обучения на платформе SAP
Автоматизация смешанного обучения на платформе SAP
molga-ru
 

Viewers also liked (11)

Q7. LOOKING BACK AT THE PRELIMINARY TASK, WHAT DO YOU FEEL YOU HAVE LEARNT IN...
Q7. LOOKING BACK AT THE PRELIMINARY TASK, WHAT DO YOU FEEL YOU HAVE LEARNT IN...Q7. LOOKING BACK AT THE PRELIMINARY TASK, WHAT DO YOU FEEL YOU HAVE LEARNT IN...
Q7. LOOKING BACK AT THE PRELIMINARY TASK, WHAT DO YOU FEEL YOU HAVE LEARNT IN...
 
Title sequence to thrillers
Title sequence to thrillersTitle sequence to thrillers
Title sequence to thrillers
 
C++ in windows phone apps
C++ in windows phone appsC++ in windows phone apps
C++ in windows phone apps
 
.NET MF & Gadgeteer - Real Cases - NetMF@Work
.NET MF & Gadgeteer - Real Cases - NetMF@Work.NET MF & Gadgeteer - Real Cases - NetMF@Work
.NET MF & Gadgeteer - Real Cases - NetMF@Work
 
mood boards
mood boardsmood boards
mood boards
 
Внедрение ERP-систем в компаниях среднего бизнеса: практика, ошибки и возврат...
Внедрение ERP-систем в компаниях среднего бизнеса: практика, ошибки и возврат...Внедрение ERP-систем в компаниях среднего бизнеса: практика, ошибки и возврат...
Внедрение ERP-систем в компаниях среднего бизнеса: практика, ошибки и возврат...
 
Windows developer program for IoT
Windows developer program for IoTWindows developer program for IoT
Windows developer program for IoT
 
Автоматизация смешанного обучения на платформе SAP
Автоматизация смешанного обучения на платформе SAP Автоматизация смешанного обучения на платформе SAP
Автоматизация смешанного обучения на платформе SAP
 
Cutomize and Control Connected Devices
Cutomize and Control Connected DevicesCutomize and Control Connected Devices
Cutomize and Control Connected Devices
 
Why should you use Slideshare - Getting Started
Why should you use Slideshare  - Getting StartedWhy should you use Slideshare  - Getting Started
Why should you use Slideshare - Getting Started
 
Windows 10 on Raspberry PI 2
Windows 10 on Raspberry PI 2Windows 10 on Raspberry PI 2
Windows 10 on Raspberry PI 2
 

Similar to Threading model in windows store apps

Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
Muhammad Sajid
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
aviade
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 

Similar to Threading model in windows store apps (20)

Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
Web services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows FormsWeb services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows Forms
 
Asynchronous Programming in Android
Asynchronous Programming in AndroidAsynchronous Programming in Android
Asynchronous Programming in Android
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 
Lecture #2 threading, networking &amp; permissions final version #2
Lecture #2  threading, networking &amp; permissions final version #2Lecture #2  threading, networking &amp; permissions final version #2
Lecture #2 threading, networking &amp; permissions final version #2
 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background Threads
 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
 
Windows 8 BootCamp
Windows 8 BootCampWindows 8 BootCamp
Windows 8 BootCamp
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadin
 
Android OS
Android OSAndroid OS
Android OS
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Android os
Android osAndroid os
Android os
 
Tech talk
Tech talkTech talk
Tech talk
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
 
Android OS
Android OSAndroid OS
Android OS
 

More from Mirco Vanini

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
 
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)
 
Connect a chips to Azure
Connect a chips to AzureConnect a chips to Azure
Connect a chips to Azure
 
Connect a chips to Azure
Connect a chips to AzureConnect a chips to Azure
Connect a chips to Azure
 
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
 
C# on a CHIPs
C# on a CHIPsC# on a CHIPs
C# on a CHIPs
 
.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
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
 
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)
 
Async Debugging - A Practical Guide to survive !
Async Debugging - A Practical Guide to survive !Async Debugging - A Practical Guide to survive !
Async Debugging - A Practical Guide to survive !
 
IoT support for .NET Core
IoT support for .NET CoreIoT support for .NET Core
IoT support for .NET Core
 
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
 
.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
 
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?
 
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
 
Debugging with VS2019
Debugging with VS2019Debugging with VS2019
Debugging with VS2019
 
Azure Sphere
Azure SphereAzure Sphere
Azure Sphere
 
Optimising code using Span<T>
Optimising code using Span<T>Optimising code using Span<T>
Optimising code using Span<T>
 
Azure Sphere
Azure SphereAzure Sphere
Azure Sphere
 
Xe OneDay - Modernizing Enterprise Apps
Xe OneDay - Modernizing Enterprise AppsXe OneDay - Modernizing Enterprise Apps
Xe OneDay - Modernizing Enterprise Apps
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Threading model in windows store apps

  • 1. Threading model in Windows Store apps Mirco Vanini Microsoft® MVP Windows Embedded
  • 2.  Why threads?  Windows threading model  Objects and threading – Marshaling  Agile objects  Thread pool threads  Using the thread pool in Windows Runtime apps Agenda
  • 3.  Service connected world  Responsive apps  Touch-based experience  Many cores Why threads?
  • 4.  Kernel threads  Separate processes  Brokers  Async operations How Windows parallelizes for you
  • 5.  UI objects live in a UI thread  Main UI thread lasts as long as app  Most other objects can be used on any thread  We pass out work to thread pool when needed Windows threading model
  • 6.  Windows objects follow natural and familiar object rules  You control lifetime  You can use them on threads you take them to  Where you create them doesn’t constrain where you use or delete them  One of our biggest changes relative to COM Windows threading model
  • 7. Windows threading model App Windows UI Object Main UI Thread Windows Object Threadpool App Code App Code App Code Windows Object
  • 8.  Three main types of object  Thread bound – works only on the thread where it was created – most UI  Thread flexible – works on any thread, uses locking if needed to control simultaneous access  Brokered – out of process  UI runs in single threaded environment that is not reentrant (“Application STA”)  Callbacks can only enter if they are related to an outgoing call  Most non-UI runs in any thread Windows threading model
  • 10.  User interface has special threading needs  Don’t want OK to be pressed during OnCancel  UI objects are deliberately and naturally serialized  Don’t do long running work on UI thread  Instead, offload large work to thread pool with async object UI threads
  • 11.  Objects on UI threads generally don’t need locking to protect themselves  UI threads are not reentrant  UI threads can’t call each other directly  Rejected at call time in Windows 8.1  Use dispatcher or async object to avoid UI threads
  • 12.  No long delays allowed on UI threads  Most classic waiting primitives are inappropriate  Windows will terminate unresponsive apps  Instead, use UI-safe primitives  C#: await  C++: create_task  JS: promise UI threads
  • 13.  App primary UI always launched on main UI thread  Contract UI (e.g. Share) launched on separate UI thread  Main UI thread used for global state  Other UI threads for documents, contracts  Main UI thread stays alive until app dies Main UI thread
  • 14.  XAML UI objects are thread-bound  Use dispatcher to move UI work back to relevant UI thread  Whole XAML tree must host on a single thread  XAML events will be delivered on the UI thread  Async operations started on XAML threads have results delivered back on UI thread  DirectX situation similar XAML environment threading
  • 15.  Basic WinRT protocols are threading-agnostic  IUnknown, IInspectable manages the object and its interfaces  WinRT protocols allow for some objects to have special threading requirements  WinRT captures all these concepts with marshaling Objects and threading
  • 16.  Marshaling allows an object to be used from another thread or process  Most WinRT objects do not require marshaling  Even references to out-of-process objects (proxies) are agile in WinRT  Objects decide how they are marshaled  IMarshal, INoMarshal control marshaling Marshaling
  • 17.  Agile objects are objects that can work in any thread of a process without being marshalled  Agile objects are simple to deal with  Most WinRT objects are agile  Out-of-process proxies are agile  Agile objects do not die if their original host thread dies Agile objects
  • 18.  Apartments are a COM concept that group and control thread and object lifetimes  Apartments exist in WinRT but have been made largely irrelevant by agility to reduce pain  Three types in Windows Store apps  Application single-threaded apartment (ASTA) – UI threads  Multithreaded apartment (MTA) – Thread pool  Neutral threaded apartment (NTA) – Used by WinRT to help inter- process calls Apartments
  • 19.  Where long-running work is done  Allocated, scaled and scheduled by the operating system  WinRT async operations automatically happen here  Always initialized for WinRT usage when created  Objects may be called back on any thread Thread pool threads
  • 20.  Your app can use the thread pool to accomplish work asynchronously in parallel threads  The thread pool offers more control than the asynchronous programming patterns  Submit work items, control their priority, and cancel work items  Schedule work items using timers and periodic timers  Set aside resources for critical work items  Run work items in response to named events and semaphores Using the thread pool
  • 21. Submitting a work item to the thread pool demo
  • 22. Submit a work item using a timer demo
  • 23. Create a periodic work item demo
  • 24. Respond to named events and semaphores demo
  • 25.  Use the thread pool to do parallel work in your app  Use work items to accomplish extended tasks without blocking the UI thread  Create work items that are short-lived and independent. Work items run asynchronously and they can be submitted to the pool in any order from the queue  Dispatch updates to the UI thread with the Windows.UI.Core.CoreDispatcher  Use ThreadPoolTimer.CreateTimer instead of the Sleep function  Use the thread pool instead of creating your own thread management system. The thread pool runs at the OS level with advanced capability and it is already optimized Using the thread pool – Do’s
  • 26.  Don't create periodic timers with a period value of <1 millisecond (including 0). This will cause the work item to behave as a single-shot timer  Don't submit periodic work items that take longer to complete than the amount of time you specified in the period parameter  Don't do any extensive work in the UI dispatch handler. The handler provided to the UI core dispatcher runs in the UI thread  Don't try to send UI updates (other than toasts and notifications) from a work item running in a background task. Instead, use background task progress and completion handlers  Don't try to create work item handlers that use the async keyword Using the thread pool – Dont's
  • 27.  WinRT designed to make threading natural, simple, and familiar  Don’t block the UI thread  Use async for long running operations  Use the thread pool to accomplish work asynchronously in parallel threads Recap
  • 28. Q&A