Presentation is loading. Please wait.

Presentation is loading. Please wait.

Asynchronous programming Using Task, async and await Asynchronous programming1.

Similar presentations


Presentation on theme: "Asynchronous programming Using Task, async and await Asynchronous programming1."— Presentation transcript:

1 Asynchronous programming Using Task, async and await Asynchronous programming1

2 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 programming2

3 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 async if there is an await statement inside the method Example: GuiExampleAsyncWait Asynchronous programming3

4 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 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 programming4

5 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, 5 th 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://www.pearsoninternationaleditions.com/Sitemap/Deitel/ http://wps.pearsoned.co.uk/wps/media/access/Pearson_Default/15358/15727496/login.htm l http://wps.pearsoned.co.uk/wps/media/access/Pearson_Default/15358/15727496/login.htm l Asynchronous programming5


Download ppt "Asynchronous programming Using Task, async and await Asynchronous programming1."

Similar presentations


Ads by Google