110 likes | 412 Views
Asynchronous programming. Using Task, async and await. Responsive user interfaces. Users expect modern user interfaces to be responsive If the user interface must not “freeze” if the user starts a long-running task. Example long-running tasks Sending or receiving data on a network
E N D
Asynchronous programming Using Task, async and await Asynchronous programming
Responsive user interfaces • Users expect modern user interfaces to be responsive • If the user interface must not “freeze” if the user starts a long-running task. • Example long-running tasks • Sending or receiving data on a network • Communication with a potentially slow server • Including database servers, web servers, etc. • Performing time consuming calculations • Reading or writing files on the local hard disk • When the user initiates a task that is assumed to be long-running we must execute the task in a separate thread • “Separate” means not in the GUI thread Asynchronous programming
Keywords: await and async • Two C# keywords: await + async • Syntax: await expression • Example: Await Task.whenAll(task1, task2, …., taskN) • Awaits termination of all task listed • await is used to await(!) the termination of a task • Normally waiting for the result of the task. • In the meantime the method that called the method containing the await will execute • When the awaited expression has terminated, control comes back to the method … • Which can then use the result to display, etc. • A method is declared asyncif there is an await statement inside the method • Example: GuiExampleAsyncWait Asynchronous programming
API async methods • Some classes has support for async programming • Example: HttpClient • With HttpClient you can download the contents of a document specifying the documents URL • Task<string> getStringTask = httpClient.getStringAsync(“http://www.easj.dk/”); • String urlContents = await getStringTask; • http://msdn.microsoft.com/en-us/library/hh191443.aspx • Example: SimpleBrowserAsync • System.IO.Stream has some async methods Asynchronous programming
References and further readings • MSDN Asynchronous Programming with Async and Await • http://msdn.microsoft.com/en-us/library/hh191443.aspx • John Sharp: Microsoft Visual C# 2012 Step by Step, • Chapter 24 Improving Response Time by Performing Asynchronous Operations, page 585-599 • Deitel & Deitel: Visual C# 2013, How To Programing, 5th edition, Pearson 2014 • Chapter 28 Asynchronous Programming with async and await, 26 pages • Available as a web-only chapter from http://www.pearsoninternationaleditions.com/Sitemap/Deitel/, Companion Web site • http://wps.pearsoned.co.uk/wps/media/access/Pearson_Default/15358/15727496/login.html Asynchronous programming