1.利用WebClient访问服务方式
public void startFun(string name)
{
string urlString = http://baidu.com;
webClientObj = new WebClient();
webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler (webClientObj_DownloadStringCompleted);
webClientObj.DownloadStringAsync(new Uri(urlString));
}
void webClientObj_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
test_fun(e.Result);
}
else
{
MessageBox.Show(e.Error.InnerException.Message);
}
}
public void test_fun(string str)
{
MessageBox.Show(str);
}
2.利用WebClient方式异步访问服务
//定义全局变量
List
WebClient webClientObj = null;
public void startFun(string name)
{
for (int i = 0; i <4; i++ )
{
urlString = “url string ”+i; urlStringList.Add(urlString);
}
webClientObj = new WebClient();
webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler (webClientObj_DownloadStringCompleted);
if (uriStringList != null && uriStringList.Count != 0)
webClientObj.DownloadStringAsync(new Uri(uriStringList[0]), "0");
}
void webClientObj_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
int idx = Convert.ToInt32((string)e.UserState);
test_fun(e.Result);
if (idx < uriStringList.Count - 1)
{
webClientObj.DownloadStringAsync(new Uri(urlStringList[idx + 1]), "" + (idx + 1));
}
else
{
//code ….
}
}
else
{
MessageBox.Show(e.Error.InnerException.Message);
}
}
public void test_fun(string str)
{
MessageBox.Show(str);
}