Tôi có 3 lớp là Login, Barcode và Main.
Lớp đăng nhập chỉ chứa xác thực của người dùng.
lớp mã vạch có đoạn mã sau đoạn:Làm cách nào để tránh trùng lặp đăng ký sự kiện?
class Barcode
{
public delegate void BarcodeReadHandler(object sender, BarcodeEventArgs e);
public event BarcodeReadHandler BarcodeReadOut;
public Barcode()
{
//.. some codes for getting data on the scanner
BarcodeEventArgs args = new BarcodeEventArgs(scannedData);
BarcodeReadOut(this, args);
}
}
Trong thời gian ở lớp học chính, các subsciption của sự kiện mã vạch được thực hiện:
public partial class Main : Form
{
private Barcode barcode = null;
public Main()
{
barcode.BarcodeReadOut += new barcode.BarcodeReadHandler(getBarcodeStr);
}
//This is called before log-out.
public void removeInstance()
{
barcode.BarcodeReadOut -= new barcode.BarcodeReadHandler(getBarcodeStr);
}
private void getBarcodeStr(object sender, BarcodeEventArgs e)
{
//some code
}
}
Việc sao thuê bao sự kiện xảy ra khi tôi cố gắng đăng xuất và đăng nhập lại.
Khi tôi cố gỡ lỗi, BarcodeReadOut được gọi hai lần.
Khi đăng xuất, removeInstance() được gọi và biểu mẫu Chính là Close() và Dispose() trước khi mở màn hình đăng nhập.
Ai đó có thể giúp tôi về cách tôi có thể tránh trùng lặp các sự kiện đã nói không?
Tôi cũng đã làm điều này trước khi đăng ký sự kiện này nhưng không có gì xảy ra:
public Main()
{
barcode.BarcodeReadOut -= new barcode.BarcodeReadHandler(getBarcodeStr);
barcode.BarcodeReadOut += new barcode.BarcodeReadHandler(getBarcodeStr);
}
bạn có thể xóa tất cả eventsubscriptions với phản xạ. Hãy xem tại đây http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control –
bạn có thể kiểm tra 'mã vạch.BarcodeReadOut == null' – Hassan
Liên kết ở trên là tốt, nhưng hãy chắc chắn để đọc nó thông qua, như là câu trả lời chấp nhận dường như không phải là tốt nhất. – TaW