Tôi đang sử dụng đoạn mã sau:Điều gì có thể gây ra lỗi "Không thể truy cập đối tượng được xử lý" trong WCF?
private WSHttpBinding ws;
private EndpointAddress Srv_Login_EndPoint;
private ChannelFactory<Srv_Login.Srv_ILogin> Srv_LoginChannelFactory;
private Srv_Login.Srv_ILogin LoginService;
Các Login là constructor của tôi:
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);
}
Và tôi đang sử dụng dịch vụ theo cách này:
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();
}
}
Khi người dùng nhập vào một tên người dùng và mật khẩu hợp lệ, mọi thứ đều ổn. Khi người dùng nhập vào tên người dùng và mật khẩu sai, lần thử đầu tiên một cách chính xác sẽ hiển thị một thông báo "Không Enter", nhưng lần thử thứ hai, người dùng nhìn thấy thông báo này:
{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()
Làm thế nào tôi có thể sửa chữa mã của tôi để ngăn chặn điều này lỗi xảy ra?
Cảm ơn @Conrad nhưng điều kỳ lạ là tôi sử dụng mã phong cách này trên các hình thức khác nhưng họ làm việc correctly.Why Close() Phương pháp xử lý đối tượng của tôi Đây có phải là hành vi bình thường không? – Arian
có, điều đó là bình thường. Đóng và Vứt bỏ thường làm điều tương tự. –
Tôi không thực sự hiểu.Tại sao mã này: LoginService = Srv_LoginChannelFactory.CreateChannel(); Xem xét rằng nhà nước là đóng cửa, tôi sẽ tạo một trường hợp mới và trạng thái đóng không phải là vấn đề – Arian