TAP into async programming

Slides:



Advertisements
Similar presentations
Parallel Extensions to the.NET Framework Daniel Moth Microsoft
Advertisements

Lecture 5 Concurrency and Process/Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
Cole Durdan.  What is asynchronous programming?  Previous patterns  Task Based Async Programming .NET 4.5 Keywords  What happens in an async. method?
Lessons learned from developing a Windows 8 Metro application in C# Frode Nilsen Nilsen Labs Ticki.
{ async patterns } - or - using the asynchronous library in the.Net 4.5 Framework for more than keeping your UI responsive.
Async Programming WITH ASYNC TASK
Lecture 4 Thread Concepts. Thread Definition A thread is a lightweight process (LWP) which accesses a shared address space provided by by the parent process.
Modified from Silberschatz, Galvin and Gagne ©2009 Lecture 7 Chapter 4: Threads (cont)
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
Chapter 5 Processes and Threads Copyright © 2008.
Threads Section 2.2. Introduction to threads A thread (of execution) is a light-weight process –Threads reside within processes. –They share one address.
Persistent State Service 1 Performance, Scalability and Management  Topic  Refining the object model  Threading models  Distributed callbacks  Iterators.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
Performance Management 1 Performance, Scalability and Management  Topic  Refining the object model  Threading models  Distributed callbacks  Iterators.
1 School of Computing Science Simon Fraser University CMPT 300: Operating Systems I Ch 4: Threads Dr. Mohamed Hefeeda.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Lesson 3 Remote Method Invocation (RMI) Mixing RMI and sockets Rethinking out tic-tac-toe game.
Fundamentals of Python: From First Programs Through Data Structures
Joe Hummel, PhD Technical Staff: Pluralsight Adjunct Professor: UIC, LUC
Pattern Oriented Software Architecture for Networked Objects Based on the book By Douglas Schmidt Michael Stal Hans Roehnert Frank Buschmann.
A Revolutionary Programming Pattern that Will Clean up your Code : Coroutines in C++ David Sackstein ACCU 2015.
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Parallel Programming: Responsiveness vs. Performance Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois,
SIMPLE PARALLEL PROGRAMMING WITH PATTERNS AND OMNITHREADLIBRARY PRIMOŽ GABRIJELČIČ SKYPE: GABR42
public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(()
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois, Chicago stuff:
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Future of VB and C# Lucian Wischik VB Language PM Microsoft.
Copyright ©: University of Illinois CS 241 Staff1 Threads Systems Concepts.
WHO WILL BENEFIT FROM THIS TALK TOPICS WHAT YOU’LL LEAVE WITH ASP.NET developers, including Web Forms & MVC History of async programming in.NET How async.
Synchronizing threads, thread pools, etc.
CS333 Intro to Operating Systems Jonathan Walpole.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Developing Applications with the CSI Framework A General Guide.
Asynchronous Programming Writing Asynchronous Code in C# SoftUni Team Technical Trainers Software University
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Operating Systems CSE 411 CPU Management Sept Lecture 10 Instructor: Bhuvan Urgaonkar.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
By: Rob von Behren, Jeremy Condit and Eric Brewer 2003 Presenter: Farnoosh MoshirFatemi Jan
Slide 1. Agenda  Introduction to Windows Workflow What is it? What are activities? Hosting  Out of the box Activities  Custom Activities and Dependency.
Synchronization These notes introduce:
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET library developers : with knowledge of async/await in C# / VB interested in low-level.
2/20/2016 EEC492/693/793 - iPhone Application Development 12/20/2016 EEC492/693/793 - iPhone Application Development 1 EEC-492/693/793 iPhone Application.
CSE 434: Computer Networks Project Single vs. Per Connection vs. Pooling Threading Techniques Dominic Hilsbos, Dorothy Johnson, Chris Volpe, Andy Wong,
Patterns of Parallel Programming with.NET 4 Stephen Toub Principal Architect Parallel Computing Platform Microsoft Corporation
E81 CSE 532S: Advanced Multi-Paradigm Software Development Chris Gill Department of Computer Science and Engineering Washington University in St. Louis.
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET developers: familiar with parallel programming support in Visual Studio 2010 and.NET.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
Asynchronous Programming Writing Concurrent Code in C# SoftUni Team Technical Trainers Software University
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
THE FUTURE OF C#: GOOD THINGS COME TO THOSE WHO ‘AWAIT’ Joseph Albahari SESSION CODE: DEV411 (c) 2011 Microsoft. All rights reserved.
Introduction to threads
Top 10 Entity Framework Features Every Developer Should Know
TechEd /6/2018 6:15 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
CS399 New Beginnings Jonathan Walpole.
Async or Parallel? No they aren’t the same thing!
Staying Afloat in the .NET Async Ocean
12 Asynchronous Programming
Build /2/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Why Threads Are A Bad Idea (for most purposes)
Building Web Applications with Microsoft ASP
C# - Razor Pages Db/Scaffolding/Async
Why Threads Are A Bad Idea (for most purposes)
Why Threads Are A Bad Idea (for most purposes)
03 | Async Programming & Networking Intro
CMSC 202 Threads.
Presentation transcript:

TAP into async programming Chris Dahlberg

Platinum Sponsors Silver Sponsors Gold Sponsors

Threading Models Single-Threaded Explicit Thread Management Thread Pool Asynchronous Programming Model (APM) Event-Based Asynchronous Pattern (EAP) Task-Based Asynchronous Pattern (TAP) Async/Await

Single-Threaded Simplest Available in all .NET versions

Explicit Thread Management Varying complexity Available in all .NET versions

Thread Pool Simple Available in all .NET versions

Event-Based Asynchronous Pattern Not simple Available in .NET 2.0 and newer

Asynchronous Programming Model Not simple Available in .NET 2.0 and newer

Task-Based Asynchronous Pattern (TAP) Simple Available in .NET 4.0 and newer

Async/Await Simple Available in .NET 4.5 and newer

Why Use Async/Await? Simplicity Single-Threaded: Async/Await: Can be nearly as simple as single-threaded code Single-Threaded: Async/Await:

Why Use Async/Await? (cont’d) Performance Run IO-bound code asynchronously Avoid blocking GUI threads Use IIS worker threads more efficiently Run CPU-bound code in parallel More efficiently use all available CPU cores

WCF Service Performance Example Server Azure VM, Single CPU Client Laptop with Core i7 CPU 150 requesting threads GetCurrentTimeSlow IIS reached 118 threads 468 requests per second GetCurrentTimeAsync IIS stayed at 20 threads 480 requests per second

Parallel Performance Example Run on a 4-core CPU GetNumber 1.83 seconds GetNumberAsync 0.55 seconds

How Async/Await Works If a Task is completed when awaited, await runs synchronously If a Task is not yet completed when awaited: ExecutionContext (including SynchronizationContext) is saved The thread of the calling method can be used to run other code Once the awaited task completes, the method that called await continues executing using the saved ExecutionContext ASP.NET, WPF, etc. each have their own special contexts When SynchronizationContext is null, the calling method continues on the ThreadPool context

Basic Things to Know Await can only be used in methods marked with the async modifier Async methods must have a return type of Task, Task<T>, or void For methods that do not return a value, use Task For methods that return a value, use Task<T> Do not use void Async method names should have an “Async” suffix Sync: string GetName() Async: Task<string> GetNameAsync() Tasks returned by async methods should already be started

Where to Use Async/Await Ideally, use async code pervasively “Grows like a virus” from entry point to API If necessary, use async code which… …calls other threading models …is called by other threading models

Common Async Entry Points Event handlers Windows Forms Windows Presentation Foundation Service operations Windows Communication Foundation WebAPI

Event Handler Example The only situation where async void methods should be used Event handlers typically do not include an “Async” suffix

Service Operation Example Methods in contracts should include the Async suffix The Async suffix will not be included in WSDL or visible to clients Worker threads can be freed and handle additional requests

Common Async APIs Service clients Streams Database clients Entity Framework Networking clients

Async Service Client APIs Svcutil.exe can generate Async variants of methods

Async Stream APIs Stream methods StreamReader methods ReadAsync(byte[], int, int) WriteAsync(byte[], int, int) StreamReader methods ReadBlockAsync(char[], int, int) ReadLineAsync() ReadToEndAsync() StreamWriter methods WriteAsync(string) WriteLineAsync(string)

Async Database APIs DbConnection methods DbCommand methods OpenAsync() DbCommand methods ExecuteNonQueryAsync() ExecuteReaderAsync() ExecuteScalarAsync() DbDataReader methods ReadAsync() NextResultAsync()

Async Entity Framework APIs DbSet<T> methods FindAsync IQueryable<T> methods AllAsync, AnyAsync AverageAsync, SumAsync ContainsAsync CountAsync, LongCountAsync FirstAsync, FirstOrDefaultAsync MaxAsync, MinAsync SingleAsync, SingleOrDefaultAsync ToArrayAsync, ToDictionaryAsync, ToListAsync

Async Networking Client Methods TcpClient methods ConnectAsync UdpClient methods ReceiveAsync SendAsync

Calling Other Threading Models Event-Based Asynchronous Pattern (EAP) Asynchronous Programming Model (APM)

Calling Event-Based Asynchronous Pattern

Calling Asynchronous Programming Model

Called By Other Threading Models Event-Based Asynchronous Pattern (EAP) Asynchronous Programming Model (APM) Single-threaded code

Called By Event-Based Asynchronous Pattern

Called By Asynchronous Programming Model

Called By Single-Threaded Code Don’t do it Ok, if you must do it, use Task.Run var result = Task.Run(() => DoSomethingAsync()).Result;

Best Practices Do not create async methods that contain only CPU-bound code Do not use Task.Run to create an async wrapper method around CPU-bound code Do not use async void methods except for event handlers Exceptions thrown from async void method can not be caught in a try/catch block. Tasks do not need to be disposed unless the AsyncWaitHandle property is accessed Always use .ConfigureAwait(false) in library code

Pitfalls Deadlocks Exceptions wrapped in AggregateException Thread synchronization limitations Entity Framework limitations IIS request limits

Deadlocks Multiple tasks waiting for the same SynchronizationContext To avoid, use .ConfigureAwait(false) whenever possible Non-async code waiting on an async Task To avoid, use Task.Run to run async code from non-async code

Exceptions Wrapped in AggregateException When calling .Wait() or .Result, exceptions are wrapped in an AggregateException Can use .GetAwaiter().GetResult(), which will throw the actual exception Can catch AggregateException and manually get the actual exception AggregateException.Flatten().InnerExceptions.First()

Thread Synchronization Limitations await can not be used… …within lock blocks …between Monitor.Enter and Monitor.Exit …between Mutex.WaitOne and Mutex.ReleaseMutex

Entity Framework Limitations Unable to have multiple simultaneous async operations Must use multiple DbContexts

IIS Request Limits On most non-server versions of Windows, IIS limits the number of concurrent requests to 10

Tips and Tricks Custom thread synchronization Task dependencies AsyncLazy Caching tasks TaskCompletionSource

Custom Thread Synchronization Could create your own using a combination of lock statements, ConcurrentQueues, Interlocked.CompareExchange, and TaskCompletionSources Could use an AsyncLock implementation that is already available from NuGet Nito.AsyncEx (by Stephen Cleary) https://www.nuget.org/packages/Nito.AsyncEx/ 13,987 downloads of the latest version CodeTiger.Core (by me) https://www.nuget.org/packages/CodeTiger.Core/ 55 downloads of the latest version

Task Dependencies Pass Task and Task<T> objects into other async methods

AsyncLazy Comparable to Lazy<Task<T>> Lazy<Task<T>: AsyncLazy<T>:

Caching Tasks Cache completed tasks to return from Async methods

TaskCompletionSource Provides a Task that does not itself run code Typically not needed when writing pure async code Can be used to interact with other threading models

Helpful Blogs Stephen Cleary http://blog.stephencleary.com/ Parallel Programming with .NET (Stephen Toub) http://blogs.msdn.com/b/pfxteam/