private void ButtonConnect_Click(object sender, RoutedEventArgs e) { if (IsConnecting) { return; } try { SocketFactory.CurrentRoute = ConnectionRoute.FromString(this.TextBoxIP.Text, this.TextBoxProxy.Text, Config.DefaultServerPort, Config.DefaultProxyPort); } catch (Exception) { SocketFactory.CurrentRoute = null; MessageBox.Show("Invalid address syntax"); Logger.Log("Invalid address syntax : " + this.TextBoxIP.Text, LogLevel.Warn); return; } try { IsConnecting = true; Logger.Log("Start connection to " + this.TextBoxIP.Text, LogLevel.Info); this.ButtonConnect.Content = "Connecting ..."; //SocketIdentity identity = SocketFactory.AsyncConnectForIdentity(AsyncConnect_OnSuccess, AsyncConnect_OnException); SocketFactory.AsyncConnectForIdentity(AsyncConnect_OnSuccess, AsyncConnect_OnException); } catch (Exception ex) { /// AsyncConnect 的异常在上面的 SocketAsyncExceptionCallback 中处理 /// 这里的代码应该不会执行 SocketFactory.CurrentRoute = null; Logger.Log("[Not expected exception] Connection to " + this.TextBoxIP.Text + " failed. " + ex.Message, LogLevel.Info); MessageBox.Show(ex.Message); IsConnecting = false; } /// 这里如果写 finally 的话, 会执行于异步代码 AsyncConnect 之前 /// 所以不应在这里用 finally 处理, 后续处理应该写进 AysncConnect 的代理方法内 }