Effective WinRT with C++ Tips and tricks for developing WinRT applications in C++

Slides:



Advertisements
Similar presentations
Win8 on Intel Programming Course Desktop : Sensors Cédric Andreolli Intel Software
Advertisements

What's new in Microsoft Visual C Preview
2 nd Microsoft Rotor Workshop, Pisa, April 23-25, SCOOPLI for.NET: a library for concurrent object-oriented programming Volkan Arslan, Piotr Nienaltowski.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Extensibility, Safety and Performance in the SPIN Operating System Presented by Allen Kerr.
Developing for Windows 8/WinRT Session 4 Fundamentals Kevin Stumpf.
Async Programming WITH ASYNC TASK
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
I/O Hardware n Incredible variety of I/O devices n Common concepts: – Port – connection point to the computer – Bus (daisy chain or shared direct access)
04/16/2010CSCI 315 Operating Systems Design1 I/O Systems Notice: The slides for this lecture have been largely based on those accompanying an earlier edition.
Operating Systems.
Check Disk. Disk Defragmenter Using Disk Defragmenter Effectively Run Disk Defragmenter when the computer will receive the least usage. Educate users.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Windows Core OS Services JavaScript (Chakra) C C++ C# VB Metro style apps Communication & Data Application Model Devices & Printing WinRT APIs Graphics.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
I/O Systems ◦ Operating Systems ◦ CS550. Note:  Based on Operating Systems Concepts by Silberschatz, Galvin, and Gagne  Strongly recommended to read.
‘Metro’ / Modern – ‘WinRT’ Also known as ‘Windows Store Apps’ --o-0-o-- Windows 8 comes as two parts Win32 and WinRT The Traditional Desktop is Win32 The.
Best Practices for.NET Development Thom Robbins
Socket Programming References: redKlyde ’ s tutorial set Winsock2 for games (gamedev.net)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
M i SMob i S Mob i Store - Mobile i nternet File Storage Platform Chetna Kaur.
I/O Systems I/O Hardware Application I/O Interface
Contact Information Office: 225 Neville Hall Office Hours: Monday and Wednesday 12:00-1:00 and by appointment.
June 6 th – 8 th 2005 Deployment Tool Set Synergy 2005.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Logging & Special Situations Steve Chenoweth Office: Moench Room F220 Phone: (812)
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Introduction to Building Windows 8.1 & Windows Phone Applications.
PVSSProxy The first piece of the MACS procedure framework (ProShell) Angela Brett.
C# Versus Java Author: Eaddy, Marc Source: Software Tools for the Professional Programmer. Dr. Dobb's Journal. Feb2001, Vol. 26 Issue 2, p74 Hong Lu CS699A.
GTK Binding for Alice Robert Grabowski Eine GTK-Schnittstelle für Alice.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 13: I/O Systems I/O Hardware Application I/O Interface Kernel I/O Subsystem.
Asynchronous Programming Writing Asynchronous Code in C# SoftUni Team Technical Trainers Software University
13 June 2001M.Al-Turany/Root20011 Mohammad Al-Turany Go4 GSI Darmstadt 13 June 2001.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Building Windows Runtime Components in C++ Harry Pierson Program Manager, Windows Runtime Experience Team Microsoft Corporation.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Async Made Simple with C++ PPL
04 |Sharing Code Between Windows 8 and Windows Phone 8 in Visual Studio Ben Riga
Unit 4: Processes, Threads & Deadlocks June 2012 Kaplan University 1.
Silberschatz, Galvin, and Gagne  Applied Operating System Concepts Module 12: I/O Systems I/O hardwared Application I/O Interface Kernel I/O.
Random Logic l Forum.NET l State Machine Mechanism Forum.NET 1 st Meeting ● December 27, 2005.
Singleton Academy, Pune. Course syllabus Singleton Academy Pune – Course Syllabus1.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
What is the Windows Runtime? Devices Sensor s Geolocation Portabl e NFC Communications & Data Contracts XML Web SMS Networking Notifications Local.
SPL/2010 Reactor Design Pattern 1. SPL/2010 Overview ● blocking sockets - impact on server scalability. ● non-blocking IO in Java - java.niopackage ●
Sockets A popular API for client-server interaction.
RealTimeSystems Lab Jong-Koo, Lim
Chapter 4: Threads Modified by Dr. Neerja Mhaskar for CS 3SH3.
Exceptional Control Flow
Object Oriented Programming in
Introduction to Operating Systems
Chapter 4: Threads.
Unit testing your metro style apps built using XAML
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Thread Fundamentals Header Advanced .NET Threading, Part 1
Async or Parallel? No they aren’t the same thing!
Java programming lecture one
CSCI 315 Operating Systems Design
Chapter 4: Threads.
Creating Windows Store Apps Using Visual Basic
I/O Systems I/O Hardware Application I/O Interface
Build /2/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
4/9/ | Contracts © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Device Access Tomas Lukša.
Native Integration Module #3 of 6.
Threads CSE 2431: Introduction to Operating Systems
Threads and concurrency / Safety
Presentation transcript:

Effective WinRT with C++ Tips and tricks for developing WinRT applications in C++

Effective WinRT with C++ How WinRT works with C++ Thread safety ▫Thread-safe singletons ▫Using lambdas for callbacks  Using the PPL  Exception handling General hints with WinRT ▫Error handling for permissions ▫Using delegates for callbacks

How WinRT works with C++ C++ implementation choices: ▫XAML based. ▫DirectX (Direct2D and/or Direct3D) based. ▫A subset of win32 API is available. Windows Store apps are sandboxed, so there are some limitations. ▫Disk and hardware access is restricted. ▫Fully multithreaded design.

Using C++ to implement WinRT classes public interface: ▫WinRT types and conventions only. private (or internal ) interface: ▫Standard C++ containers, classes and conventions can be used. Enumerated types: ▫Strongly typed enums ( enum class ) are accepted.

Using new standard language features WinRT containers can be constructed from standard library containers. Range-based for loops work with WinRT classes (include collection.h ). Move semantics is available. Lambdas are accepted as delegates/function pointers. Thread safety is very important.

Thread safety in modern C++ Example of a thread-safe singleton class Singleton { public: virtual ~Singleton(); static Singleton& Get(); private: static std::unique_ptr s_instance; static std::once_flag s_creationFlag; Singleton(); Singleton(const Singleton& other) /* = delete */; Singleton& operator=(const Singleton& other) /* = delete */; }

Thread safety in modern C++ Example of a thread-safe singleton std::unique_ptr Singletion::s_instance = nullptr; std::once_flag Singleton::s_creationFlag; Singleton& Singleton::Get() { std::call_once(s_creationFlag, []{ s_instance.reset(new Singleton); }); return *s_instance.get(); }

Multithreading in WinRT Every command* runs in its own thread. Avoid the callback spaghetti: ▫Parallel Patterns Library ▫Use delegates for event handling * That potentially lasts longer than 50 ms

Parallel Patterns Library The Parallel Patterns Library (PPL) provides an imperative programming model that promotes scalability and ease-of-use for developing concurrent applications. - MSDN (

Parallel Patterns Library Task objects, analogous to std::future objects. using namespace concurrency; task myTask([]{ do_something(); }); auto myTask = concurrency::create_task([]{ do_something(); }); // Non-blocking or blocking call to retrieve the result myTask.get(); // Blocking call, retrieves the status myTask.wait(); Allows an imperative style when launching non- blocking tasks myTask.then([]{ do_what_comes_next(); });

Asynchronous calls made easy concurrency::task Singleton::ComplexTask() { /*... */ } // Define a sequence of tasks Singleton::Get().ComplexTask().then([] { //... }).then([] { //... });

WinRT CoreDispatcher class Every XAML page can access the CoreDispatcher object through the Dispatcher member Issue tasks in the main thread, from any thread. using namespace Windows::Core::UI; using namespace Windows::System::Threading; // Non-blocking call with normal priority. Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([]{ /*...*/ })); // Check whether the current thread can be accessed Dispatcher->HasThreadAccess();

Capturing objects in task chains concurrency::task MyClass::ExecuteTask() { //... return concurrency::create_task( [this, local_variable] // <-- avoid locals by reference! { m_cached_value = local_variable; }).then([this] { }); // and so on... };

Exception handling concurrency::create_task([] { }) // A few tasks “later”....then([this](concurrency::task t) { try { t.get(); } catch(Platform::Exception^ except) { // Handle except } });

Special cases in error handling Handle connection to devices ▫Windows handles first access for you.  Geolocation, camera, phone functionality, etc. When using webcam or microphone ▫Permission errors are handled by checking:  E_ACCESSDENIED  HRESULT_FROM_WIN32(ERROR_FILE_HANDLE_REVOKED) When sending SMS (Windows Phone 8) ▫Permission errors handled by checking:  E_ACCESSDENIED

Special cases in error handling Examples of error handling for webcam capture ▫Initialization error: // (continued task chain including call to InitializeAsync).then([this](task t) { try { t.get(); } catch(Exception^ e) { if(e->HResult == E_ACCESSDENIED) // Handle permissions error else // Check if camera is not connected } ▫Spontaneous error: void CameraCallback(MediaCapture^ currentCaptureObject, MediaCaptureFailedEventArgs^ currentFailure) { if(currentFailure->Code == HRESULT_FROM_WIN32(ERROR_FILE_HANDLE_REVOKED)) // Handle revoked permissions else // Check if camera was suddenly disconnected }

Special cases in error handling Short Demonstration

Granting permissions File system access may be needed for logging ▫Add the targeted folder read/write access to  ALL APPLICATION PACKAGES

Using delegates for callbacks In WinRT applications, callbacks can be registered through a generic mechanism. Non-standard language extensions: ▫ delegate keyword. ▫ event keyword. WinRT EventRegistrationToken class: ▫Used to register the delegates for corresponding events.

Using delegates for callbacks A very simple class that reacts to events public delegate void MyEventHandler(); public ref class MyEventsManager sealed { public: static event MyEventHandler^ OnMyEvent; static void FireMyEvent() { OnMyEvent(); } };

Using delegates for callbacks Use EventRegistrationToken // Class declaration class MyClass { //... private: Windows::Foundation::EventRegistrationToken token; } // Class implementation token = MyEventsManager::OnMyEvent += ref new MyEventHandler([]{ /*... */ }); Finally, trigger the event when needed by calling MyEventsManager::FireMyEvent();

Using delegates for callbacks Short Demonstration

References and useful sources ISO Standard C++ official page ▫ MSDN (Microsoft Developer Network) ▫ CodeProject ▫ Store-app-Beginners-tutorial Marc Grégoire Blog ▫

Thank you