Skip to content

Instantly share code, notes, and snippets.

@llj098
Created May 16, 2012 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llj098/2709929 to your computer and use it in GitHub Desktop.
Save llj098/2709929 to your computer and use it in GitHub Desktop.
A Simple AsyncEnumerator Implementation
using System;
using System.Net;
using System.Collections;
using System.Collections.Generic;
class Test
{
public static void Main(string[] args) {
GetHtml();
Console.WriteLine("FINI");
Console.ReadLine();
}
private static void GetHtml2() {
WebRequest request = WebRequest.Create("Http://www.baidu.com");
request.BeginGetResponse(HandleResponse,request);
}
private static void HandleResponse(IAsyncResult ar)
{
WebRequest request = (WebRequest)ar.AsyncState;
WebResponse resp = request.EndGetResponse(ar);
Console.WriteLine("RESULT:{0}", resp.ContentLength);
}
private static void GetHtml() {
AsyncEnumerator ae = new AsyncEnumerator("");
ae.Excute(DoGetHtml(ae));
}
private static IEnumerable<int> DoGetHtml(AsyncEnumerator ae) {
WebRequest request = WebRequest.Create("Http://www.baidu.com");
request.BeginGetResponse(ae.EndCallback,request);
yield return 1;
var resp = request.EndGetResponse(ae.AsyncResult);
var l = resp.ContentLength;
Console.WriteLine("RESULT:{0}",resp.ContentLength);
request = WebRequest.Create("http://www.baidu.com?"+l.ToString());
request.BeginGetResponse(ae.EndCallback,request);
yield return 1;
resp = request.EndGetResponse(ae.AsyncResult);
Console.WriteLine("RESULT:{0}",resp.ContentLength);
yield return 2;
}
}
public class AsyncEnumerator
{
public AsyncEnumerator(string name) { }
private IEnumerable<int> m_func;
private IEnumerator<int> m_t;
public IAsyncResult AsyncResult { get; private set; }
public void Excute(IEnumerable<int> f) {
m_t = f.GetEnumerator();
try {
MoveNext();
}
finally
{
//tor.Dispose();
}
}
internal void MoveNext() {
m_t.MoveNext();
}
public void EndCallback(IAsyncResult ar) {
this.AsyncResult = ar;
MoveNext();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment