假设我有两个班级。这是第一类称为Internet的相关代码:
public void doRequest()
{
string URL = "http://localhost:4000/HomePage.aspx";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
public void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
byte[] byteArray = Encoding.UTF8.GetBytes("Test Message");
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
public void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(callbackResult);
StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream());
string result = httpWebStreamReader.ReadToEnd();
}
catch (WebException)
{
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Error: Could not reach the web service"));
}
}
此代码由名为 MainPage.xaml.cs 的类调用:
private void Button_LogIn_Click(object sender, RoutedEventArgs e)
{
Internet net = new Internet();
bool check = net.checkInternet();
if (check.Equals(false))
{
}
else
{
net.doRequest();
ClientServiceSoapClient web_service = new ClientServiceSoapClient();
web_service.LogInCompleted += new System.EventHandler<LogInCompletedEventArgs>(LogInComplete);
web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
}
}
我想要的是,如果在doRequest方法调用中发生异常,则处理异常(Internet类末尾的WebException),然后停止执行其后的代码(ClientServiceSoapClient web_service ....)。
我怎样才能做到这一点?