Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
7.1. Asynchrony: the new approach
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//7.1. Asynchrony: the new approach using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net.Http; using System.Threading; namespace Rextester { public class Program { public static void Main(string[] args) { //So the old approach was to subscribe to "work completed" event and call a non-blocking method. //Then handle result (or error) in the event handler. If you ever had to do another non-blocking call in the handler itself //then you'd do the same and end up with an event handler in an event handler, i.e. messy code. //The new approach let's you write asynchronous code that looks like synchronous, i.e. without event handlers. //Besides that errors would propagate just as in synchronous code. AsyncWork(); //it's async so returns immediately, that's why we need to Sleep() below Thread.Sleep(5000); } public static async void AsyncWork() //whenever you use await in the method, that method becomes async (note the modifier) { var client = new HttpClient(); Console.WriteLine("Current thread: {0}", Thread.CurrentThread.ManagedThreadId); var task = client.GetStringAsync("http://stackoverflow.com"); //non-blocking, returns Task<string> //do some other work here if needed await task; //suppose now you need the downloaded string, you wait on Task<string>. //while waiting you don't run on any thread. Once task is ready some thread from //thread pool will be used to execute the rest of the code. //That's why this method runs on two different threads. Console.WriteLine("Current thread: {0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("Size: {0}", task.Result.Length); } } }
Show compiler warnings
[
+
]
Show input
Compilation time: 0.12 sec, absolute running time: 5.4 sec, cpu time: 0.62 sec, average memory usage: 29 Mb, average nr of threads: 14
fork mode
|
history
|
discussion
Current thread: 5 Current thread: 9 Size: 214615