ban*_*ana 5 c# events duplication subscribe
我有3个类,即Login,Barcode和Main.
登录类只包含用户的身份验证.
条形码类具有以下代码段:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在Main类中,Barcode事件的subsciption完成:
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
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试注销并再次登录时,会发生事件订阅的重复.
当我尝试调试时,BarcodeReadOut被调用两次.
在注销中,在打开登录屏幕之前调用removeInstance()并且Main表单是Close()和Dispose().
有人可以帮助我如何避免重复上述事件?
在注册事件之前我也做过这个,但没有任何反应:
public Main()
{
barcode.BarcodeReadOut -= new barcode.BarcodeReadHandler(getBarcodeStr);
barcode.BarcodeReadOut += new barcode.BarcodeReadHandler(getBarcodeStr);
}
Run Code Online (Sandbox Code Playgroud)
您应该按如下方式添加和删除处理程序:
public partial class Main : Form
{
private Barcode barcode = null;
public Main()
{
barcode.BarcodeReadOut += getBarcodeStr;
}
//This is called before log-out.
public void removeInstance()
{
barcode.BarcodeReadOut -= getBarcodeStr;
}
private void getBarcodeStr(object sender, BarcodeEventArgs e)
{
//some code
}
}
Run Code Online (Sandbox Code Playgroud)
另外:您不需要定义自定义委托,您可以使用通用的EventHandler:
public event EventHandler<BarcodeEventArgs> BarcodeReadOut;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |