Created
May 16, 2012 12:22
-
-
Save llj098/2709929 to your computer and use it in GitHub Desktop.
A Simple AsyncEnumerator Implementation
This file contains hidden or 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.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