2 wayzinc wayzinc 于 2016.03.21 16:47 提问

C#同/异步委托使用和调用,请指教

public delegate void GetResultEventHandler(object sender, bool IsSucceed, string DataResults);
public event GetResultEventHandler OnGetInfoCompleted;
public void GetPostHtmlResults(string GetURL, int GetTimeOut)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(GetURL);
request.Method = "GET";
request.ContinueTimeout = GetTimeOut;
request.BeginGetResponse(GetInfoCompleted, request);
}
private void GetInfoCompleted(IAsyncResult asyncResult)
{
try
{
HttpWebRequest webRequest = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
Stream streamResult = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(streamResult, Encoding.UTF8);
if (OnGetInfoCompleted != null)
OnGetInfoCompleted(this, true, reader.ReadToEnd());
}
catch (WebException ex)
{
OnGetInfoCompleted(this, false, ex.Message.ToString());
}
}
请问这个同/异步委托对不对,还有怎样调用它,谢谢!

1个回答

caozhy
caozhy   Ds   Rxr 2016.03.21 18:01

从语法上说没什么问题,但是你本身GetResponseStream是同步的,所以包装成异步的没有实际意义。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!