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; Example: SimpleBrowserAsync System.IO.Stream has some async methods Asynchronous programming4

5 References and further readings MSDN Asynchronous Programming with Async and Await John Sharp: Microsoft Visual C# 2012 Step by Step, Chapter 24 Improving Response Time by Performing Asynchronous Operations, page 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 Companion Web site l l Asynchronous programming5


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

Similar presentations


Ads by Google