Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
7.1. Asynchrony: the new approach
//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); } } }
run
|
edit
|
history
|
help
0
show IP
Geração de HASH do SKU pra enviar para Vtex
Working (C# thing)
Matrix Main Diagonal
Kz
adxasxd
Recursion
QLSV
172
Write a program to sort given array using bubble sort.