Created
October 29, 2010 03:05
-
-
Save koush/652813 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Collections.Generic; | |
using System.Collections; | |
using System.Net; | |
namespace test2 | |
{ | |
public static class Extensions | |
{ | |
public static Task Await(this Task task, TaskContext context) | |
{ | |
task.ContinueWith(a => context.Continue()); | |
if (task.Status != TaskStatus.Running && task.Status != TaskStatus.WaitingForActivation) | |
task.Start(); | |
return task; | |
} | |
} | |
public class TaskContext | |
{ | |
public void Continue() | |
{ | |
if (!mEnumerator.MoveNext()) | |
{ | |
mAction(); | |
} | |
} | |
IEnumerable<Task> mTasks; | |
IEnumerator<Task> mEnumerator; | |
Action mAction; | |
public void Attach(IEnumerable<Task> tasks, Action a) | |
{ | |
mAction = a; | |
mTasks = tasks; | |
mEnumerator = mTasks.GetEnumerator(); | |
mEnumerator.MoveNext(); | |
} | |
} | |
class MainClass | |
{ | |
static IEnumerable<Task> DoLongThing(TaskContext context) | |
{ | |
Console.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId); | |
var search = new WebClient().DownloadStringTask("http://koush.tandtgaming.com//test/search.txt"); | |
yield return search.Await(context); | |
Console.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId); | |
var url = "http://www.google.com/search?q=" + search.Result; | |
var google = new WebClient().DownloadStringTask(url); | |
yield return google.Await(context); | |
Console.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId); | |
Console.WriteLine(google.Result); | |
yield break; | |
} | |
public static void Main(string[] args) | |
{ | |
bool done = false; | |
var search = new WebClient().DownloadStringTask("http://koush.tandtgaming.com//test/search.txt"); | |
Console.WriteLine(search.Result); | |
TaskContext context = new TaskContext(); | |
context.Attach(DoLongThing(context), () => done = true); | |
while (!done) | |
{ | |
Thread.Sleep(1000); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment