Skip to content

Instantly share code, notes, and snippets.

@jpolvora
Last active November 17, 2023 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpolvora/4653838 to your computer and use it in GitHub Desktop.
Save jpolvora/4653838 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
namespace AsyncKonsole
{
class Program
{
static string htmlBlogspot;
static string htmlGoogle;
public static void Main(string[] args)
{
Coroutine.BeginExecute(MultipleRoutines());
Console.ReadLine();
}
static IEnumerable<Routine> MultipleRoutines() {
yield return FirstRoutine;
if (htmlBlogspot.Length < 1000) {
Console.WriteLine(htmlBlogspot);
yield break;
}
//executa e aguarda a segunda operação
yield return SecondRoutine;
//imprime quando estiver pronto
Console.WriteLine(htmlGoogle);
}
static void FirstRoutine(Action completed) {
var webClient1 = new WebClient();
webClient1.DownloadStringCompleted += (s1,e1) => {
htmlBlogspot = e1.Result;
completed();
};
webClient1.DownloadStringAsync(new
Uri("http://silverlightrush.blogspot.com"));
}
static void SecondRoutine(Action completed) {
var webClient2 = new WebClient();
webClient2.DownloadStringCompleted += (s2, e2) => {
htmlGoogle = e2.Result;
completed();
};
webClient2.DownloadStringAsync(new Uri("http://google.com"));
}
}
public delegate void Routine(Action callback);
public static class Coroutine {
public static void BeginExecute(this IEnumerable<Routine> enumerable) {
Continue(enumerable.GetEnumerator());
}
static void Continue(IEnumerator<Routine> enumerator) {
if (!enumerator.MoveNext()) {
enumerator.Dispose();
} else {
var routine = enumerator.Current;
routine.Invoke(() => Continue(enumerator));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment