340 likes | 583 Views
DEV340. Tackle the Complexity of Async Calls in WPF and Silverlight. Brian Noyes Chief Architect IDesign Inc ( www.idesign.net ) . About Brian. Publishing Developers Guide to Microsoft Prism 4, O’Reilly & Assoc., March 2011
E N D
DEV340 Tackle the Complexity of Async Callsin WPF and Silverlight Brian Noyes Chief Architect IDesign Inc (www.idesign.net)
About Brian • Publishing • Developers Guide to Microsoft Prism 4, O’Reilly & Assoc., March 2011 • Developing Applications with Windows Workflow Foundation, LiveLessons training DVD, June 2007 • Smart Client Deployment with ClickOnce, Addison Wesley, January 2007 • Data Binding in Windows Forms 2.0, Addison Wesley, January 2006 • MSDN Magazine, MSDN Online, CoDe Magazine, The Server Side .NET, asp.netPRO, Visual Studio Magazine • Speaking • Microsoft TechEd US, Europe, Malaysia, Visual Studio Connections, DevTeach, INETA Speakers Bureau, MSDN Webcasts Chief ArchitectIDesign Inc. (www.idesign.net) Microsoft Regional Director(www.theregion.com) Microsoft MVP Silverlight E-mail: brian.noyes@idesign.net Twitter: @briannoyes Blog: http://briannoyes.net
Agenda • Multithreading overview • Working with the Dispatcher • Async calling patterns • Begin/End and Async/Completed • Task Parallel Library / PFX / PLINQ • Task-based Async Pattern (Async CTP) • Reactive Extensions
Commandments of UI Multithreading • Thou shalt not block the UI thread • Thou shalt not access UI objects on a non-UI thread • Thou shalt not access variables on multiple threads without protection (locks)
Multithreading – The Risk • Concurrent access to memory • Member / static variables • Two or more threads • One or more reads • One or more writes • Can corrupt memory depending on when threads are scheduled • Need synchronization locks • Deep end of the programming pool
UI Multithreading • Silverlight and WPF use a single thread for UI concerns • WPF – startup thread of the app • Silverlight - Browser thread • Can have many other threads executing in the UI application • Async method calls • Worker threads • Service callbacks
Agenda • Multithreading overview • Working with the Dispatcher • Async calling patterns • Begin/End and Async/Completed • Task Parallel Library / PFX / PLINQ • Task-based Async Pattern (Async CTP) • Reactive Extensions
Using Dispatcher • Used to get execution on the UI thread when you are on another thread • (WPF Only) Synchronous from calling thread • Blocking until unit of work complete on UI thread • Async from calling thread • Non-blocking • Work is dispatched asynchronously to the UI thread when current thread time slice is complete • Checking to see if dispatch is needed:
SynchronizationContexts • Dispatcher uses DispatcherSynchronizationContext under the covers • Derived from SynchronizationContext • Standard thread dispatch pattern in .NET for objects with thread affinity • Windows Forms, ASP.NET, WPF, Workflow also have implementations • Multithreaded mechanisms can use this to auto-dispatch to the UI thread • Async/Completed pattern • Task class from TPL • Reactive Extensions • Task-based Async Pattern (Async CTP) • WCF message dispatching
Working with the Dispatcher Brian Noyes Chief Architect IDesign Inc. (www.idesign.net) demo
Agenda • Multithreading overview • Working with the Dispatcher • Async calling patterns • Begin/End and Async/Completed • Task Parallel Library / PFX / PLINQ • Task-based Async Pattern (Async CTP) • Reactive Extensions
Begin/End and Async/Completed Patterns Brian Noyes Chief Architect IDesign Inc. (www.idesign.net) demo
Begin/End Async Pattern • Introduced in .NET 1.0 / all platform variants • Most powerful pattern • Polling or callbacks for completion • Can pass state when invoking • Can access waithandles for each invocation for blocking ops • Most complex pattern • More complex method signatures • Have to hold on to IAsyncResult or use callbacks • Have to hold on to object that async work was invoked on • Callbacks happen on background thread
Async/Completed Pattern • Introduced in .NET 2.0 • Implemented by some APIs, BackgroundWorker, WCF Proxies • MyOperationAsync method • Invokes target method (MyOperation) on background thread • Same parameter list as target method • void return type • MyOperationCompleted event • Fired by runtime when background thread operation completes • Automatically marshaled the event handler call to the UI thread (if needed) • Event arguments contain strongly typed results • Event arguments contain exception if one was raised
BackgroundWorker • Introduced in .NET 2.0 • Available in WPF, Silverlight, Silverlight for Windows Phone • Implements Async/Completed pattern • Point DoWork event at method to execute on background thread • Supports cancellation
Agenda • Multithreading overview • Working with the Dispatcher • Async calling patterns • Begin/End and Async/Completed • Task Parallel Library / PFX / PLINQ • Task-based Async Pattern (Async CTP) • Reactive Extensions
Task Parallel Library • Shipped in .NET 4 • Only available in full .NET Framework at this time • Planned to be supported in future version of Silverlight • Use Task class to point to asynchronous work • Dispatches to thread pool thread • Enhances thread management in pool • Continuations • Can schedule on the user interface thread • Exception callbacks • Cancellation supported
Parallel Framework (PFX) / PLINQ • Allows simple data parallelization • Parallel.For and Parallel.ForEach methods • PLINQ .AsParallel extension • Executes subsequent LINQ operations concurrently • Smart scheduling of the “appropriate” number of threads • Based on cores, target method complexity, collection size, etc • Items in collection need to be independent
TPL and PLINQ Brian Noyes Chief Architect IDesign Inc. (www.idesign.net) demo
Agenda • Multithreading overview • Working with the Dispatcher • Async calling patterns • Begin/End and Async/Completed • Task Parallel Library / PFX / PLINQ • Task-based Async Pattern (Async CTP) • Reactive Extensions
Task-based Async Pattern (Async CTP) • New keywords being added to C# and VB • Will be released with the next version • Allows you to write code that looks synchronous, but executes asynchronous • Compile time code generation into async patterns • Public CTP available
Task-based Async Pattern (Async CTP) • Uses Task class from Task Parallel Library • New keywords • await • async • Naming and return type conventions • Task<T>, XXXAsync
Task-based Async Pattern (Async CTP) Brian Noyes Chief Architect IDesign Inc. (www.idesign.net) demo
Agenda • Multithreading overview • Working with the Dispatcher • Async calling patterns • Begin/End and Async/Completed • Task Parallel Library / PFX / PLINQ • Task-based Async Pattern (Async CTP) • Reactive Extensions
Reactive Extensions (Rx) • AKA LINQ to Events • Available now as add-ons • .NET Framework, Silverlight, SL for Windows Phone, JavaScript • Allows you to treat events and async operations as collections • Allows use of LINQ operations to logically filter, join, order, etc
Reactive Extensions • IObservable<T> / IObserver<T> interfaces • Duals of IEnumerable<T> / IEnumerator<T> • Allows LINQ syntax • You provide an IObserver implementation that handles • OnNext – the next event occurred • OnCompleted – Events or async operation is done • OnError – exception handling • Clean API for events and async ops • Things that are inherently a chain of asynchronously produced data that you want to consume
Reactive Extensions (Rx) Brian Noyes Chief Architect IDesign Inc. (www.idesign.net) demo
What Should I Use? • Near term: • Async/Completed if you want cleanest/safest/easiest code • TPL if you want to start moving into the Task-based world • Rx for combining multiple asynchronous sources • PLINQ/Parallel for parallel collection processing • Sightly longer term: • Primarily Task-based Async Pattern • Secondarily Rx for compositional scenarios • PLINQ/Parallel for parallel collection processing
Resources • DEV324 | C# and Visual Basic Future: Async Made Simple – Alex Turner, Wed May 18 3:15 pm • Deeper dive into Task-based Async Pattern • Programming .NET Components, 2nd Edition, Juval Lowy, O’Reilly & Assoc.http://oreilly.com/catalog/9780596102074 • Reactive Extensionshttp://msdn.microsoft.com/en-us/devlabs/gg577609 • Async CTPhttp://msdn.microsoft.com/en-us/vstudio/gg316360 E-mail: brian.noyes@idesign.net Blog: http://briannoyes.net Twitter: @briannoyes
Web Track Resources • http://www.asp.net/ • http://www.silverlight.net/ • http://www.microsoft.com/web/gallery/ • http://www.iis.net/ • http://weblogs.asp.net/Scottgu/ • http://www.hanselman.com/blog/
Resources • Connect. Share. Discuss. http://northamerica.msteched.com Learning • Sessions On-Demand & Community • Microsoft Certification & Training Resources www.microsoft.com/teched www.microsoft.com/learning • Resources for IT Professionals • Resources for Developers • http://microsoft.com/technet • http://microsoft.com/msdn