我正在使用以下代码:
private WSHttpBinding ws;
private EndpointAddress Srv_Login_EndPoint;
private ChannelFactory<Srv_Login.Srv_ILogin> Srv_LoginChannelFactory;
private Srv_Login.Srv_ILogin LoginService;
登录是我的构造函数:
public Login()
{
InitializeComponent();
ws = new WSHttpBinding();
Srv_Login_EndPoint = new EndpointAddress("http://localhost:2687/Srv_Login.svc");
Srv_LoginChannelFactory = new ChannelFactory<Srv_Login.Srv_ILogin>(ws, Srv_Login_EndPoint);
}
我以这种方式使用服务:
private void btnEnter_Click(object sender, EventArgs e)
{
try
{
LoginService = Srv_LoginChannelFactory.CreateChannel();
Srv_Login.LoginResult res = new Srv_Login.LoginResult();
res = LoginService.IsAuthenticated(txtUserName.Text.Trim(), txtPassword.Text.Trim());
if (res.Status == true)
{
int Id = int.Parse(res.Result.ToString());
}
else
{
lblMessage.Text = "Not Enter";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Srv_LoginChannelFactory.Close();
}
}
当用户输入有效的用户名和密码时,一切正常。当用户输入错误的用户名和密码时,第一次尝试正确显示“未输入”消息,但在第二次尝试时,用户看到此消息:
{System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.ServiceModel.ChannelFactory`1[Test_Poosesh.Srv_Login.Srv_ILogin]'.
at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposed()
at System.ServiceModel.ChannelFactory.EnsureOpened()
at System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address, Uri via)
at System.ServiceModel.ChannelFactory`1.CreateChannel()
如何修复我的代码以防止发生此错误?