1

2つのクラスがあるとしましょう。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 メソッド呼び出しで例外が発生した場合、例外が処理され (インターネットクラスの最後にある WebException)、その後コードの実行を停止することです (ClientServiceSoapClient web_service....)。

これどうやってするの?

4

4 に答える 4

6

ここでキーワードreturnを使用できます (これは void を返します)。私は実際に 2 回使用しました。空の if ステートメントがあるため、少し修正しました。

        private void Button_LogIn_Click(object sender, RoutedEventArgs e)
        {
            Internet net = new Internet();
            bool check = net.checkInternet(); 

            if (check.Equals(false))
                  return;

                try
                {
                    await net.doRequest(); //UPDATED THIS LINE
                    ClientServiceSoapClient web_service = new ClientServiceSoapClient();
                    web_service.LogInCompleted += new System.EventHandler<LogInCompletedEventArgs>(LogInComplete);
                    web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
                }
                catch
                {
                    //do not throw an error, instead just use the return keyword!
                    return;
                }   
        }

ただし、私には意味のない非同期メソッドを使用しています! 続行する前に結果を検証する必要がある場合は、非同期で呼び出す必要はありません。シリアルで実行する必要があります。または、awaitキーワードを確認してください。

于 2013-04-23T13:59:50.253 に答える
2

タイトルは、実行を停止し、関数から戻らないように求めています。そのため、メイン関数にいない場合で、例外をスローしてメインで再びキャッチしたくない場合は、Exit コードで Environment.Exit() を使用できます。https://msdn.microsoft. com/en-us/library/ms681382(v=vs.85)

Environment.Exit(ERROR_INVALID_COMMAND_LINE)
于 2017-06-16T19:46:10.343 に答える
1

例外をキャッチし、何らかの処理を行ってから再スローすることで、このメソッドからのコードがそれ以上実行されないようにすることができます。

try{
   ...    
}catch(Exception ex){
   // do something with ex
   throw;
}
于 2013-04-23T14:01:12.753 に答える
1
try
{
    net.doRequest();
}
catch(Exception e)
{
    if(e is WebException)
    {
        //handle appropriately
        return; //will exit the method
    }
    else
        throw; //good idea to throw unexpected exceptions anyway
}
于 2013-04-23T14:06:32.580 に答える