0
我一直在使用AsyncEnumerator類來幫助清理我的異步代碼。問題在於yield return之後的代碼永遠不會觸發。用戶界面在單擊按鈕時調用一個調用HttpWorker對象的對象。無論點擊多少按鈕,代碼都不會超過收益回報。使用AsyncEnumerator
public void ReadFromUrl(string Url)
{
AsyncEnumerator asyncEnum = new AsyncEnumerator();
asyncEnum.BeginExecute(GetData(asyncEnum,Url), asyncEnum.EndExecute);
}
private IEnumerator<Int32> GetData(AsyncEnumerator AsyncEnum, String Url)
{
url = Url;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
request.BeginGetResponse(AsyncEnum.End(), null);
AsyncEnum.SyncContext = null;
yield return 1;
response = (HttpWebResponse)request.EndGetResponse(AsyncEnum.DequeueAsyncResult());
if (response.StatusCode == HttpStatusCode.OK)
{
// Create the stream, encoder and reader.
Stream responseStream = response.GetResponseStream();
Encoding streamEncoder = Encoding.UTF8;
StreamReader responseReader = new StreamReader(responseStream, streamEncoder);
responseAsString = responseReader.ReadToEnd();
}
else
{
throw new Exception(String.Format("Response Not Valid {0}", response.StatusCode));
}
}
我沒有看到任何錯誤。確保在* yield *之後設置斷點,步進將不起作用。 – 2010-11-10 03:34:44
你我的朋友,是一個傳奇! – deanvmc 2010-11-10 08:31:41