Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Asynchronous programming

736 views

Published on

  • Be the first to comment

Asynchronous programming

  1. 1. ASYNCHRONOUS PROGRAMMINGCode Review 4/26/13 – Chester Hartin
  2. 2. Hopes Identify where you may need asynchronousprocessing Implement it with Background workers,TaskParallel Library, or async & await pattern Learn to refactor synchronous applicationsinto become more responsive
  3. 3. Asynchronous vs. Parallel Who remembers my talk about boiling eggsusing the parallel extensions? Concurrency / Boiling several eggs simultaneously By boiling the eggs in different pots, we areboiling them in parallel to each other. Now if we do something else while they’reboiling, like cleaning up the kitchen, and wego back to them once they’re done… thattask is done asynchronously
  4. 4. Asynchronous vs. Parallel Think of parallelism as something that runsindependently at the same time as anothertask Think of asynchronous operations assomething that will let you do things in themeantime while you wait, but once it’sfinished, you receive the results
  5. 5. Asynchronous It’s common to look at asynchronousprocesses as non-blocking (ie the systemwon’t lock up, will continue). So how do we do this?
  6. 6. Synchronous Design
  7. 7. Asynchronous Design
  8. 8. Asynchronous There are several methods Threads &Thread Pooling Background workers Task Parallel Library (TPL) Asynch & await
  9. 9. Example 1 – No threading lblInfo.Text = ProcessOrder();private string ProcessOrder() {// really long task that takes for ever}
  10. 10. Example 2 – background worker //ex2 private void bgw_DoWork(object sender, DoWorkEventArgs e) { e.Result = ProcessOrder(); } private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { lblInfo.Text = e.Result.ToString() ; }
  11. 11. Example 3 – TPL (Task Parallel Library ) private void ProcessOrderContinueWith(){var task = newTask<string>(ProcessOrder);task.Start();task.ContinueWith((parentTask) => {this.Invoke(new Action(() => {lblInfo.Text = parentTask.Result;}));});lblInfo.Text = "Thinking";}
  12. 12. Example 3 – TPL (cont) What happens is we’re creating a Statemachine This handles everything in the background &keeps track of what task is running & whereso it knows where to go back
  13. 13. Example 4 -- Async & Awaitprivate async void ProcessOrderAsync(){var processOrderResult =Task<string>.Factory.StartNew(ProcessOrder);lblInfo.Text = await processOrderResult;}
  14. 14. Example 4 -- Async & Await Still a state machine, but way easier to read &implement!
  15. 15. Refactoring Using async & await allows you to utilizemost of your existing code

×