Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
7. Asynchrony
//7. Asynchrony using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net; using System.Threading; namespace Rextester { public class Program { public static void Main(string[] args) { //Asyncrony means doing non-blocking calls. Non-blocking call is the one that returns before it has done it's work. //This is blocking call: var client = new WebClient(); var content = client.DownloadString("http://stackoverflow.com"); //this will not return until web site is downloaded. Console.WriteLine(content.Length); //This is non-blocking call: client.DownloadStringCompleted += (a, b) => { if(b.Error != null) Console.WriteLine("Async error: {0}", b.Error.Message); else Console.WriteLine("Async result: {0}", b.Result.Length); }; client.DownloadStringAsync(new Uri("http://stackoverflow.com")); //this will return imediately (thus non-blocking) Thread.Sleep(5000); //let's wait //So the benefit of non-blocking calls is that, well, they don't block and you can immediately continue with other work. //Realize that reading disk can be 100 000 times slower than reading ram and reading network socket can be 1000 0000 times slower. //So instead of waiting for that you could continue immediately with something else and do your work that requires the result of io //in event handler once the call is finished. //You could achieve simillar effect by creating new thread and downloading web site in that thread. That's true except //you will end up with another thread in which you would make blocking call. And while that call will be blocked the thread //that you created will live and consume system resources. //In this async approach, the event handler will also be invoked on a different thread than the main one, but that thread will //only be started when needed (when IO completes). In short async approach is more efficient comparing to threading approach. } } }
run
|
edit
|
history
|
help
0
Fórum ➡ Prime numbers implemented using LINQ statements AND using FOR loop ♦
Code1
sdfrgthyjuytrfdf
Hello World Program
Frase
ProgramDemo
Collection_ basic datastructure brushup
Just tries to add/remove items to the list
CommandForce3
Calculate Used Unit from Readings