问题
I have a really weird problem with reading Mifare 1k card from WinForm application. The reader I'm using is a PROMAG PCR-310U smart card reader. I use this code to read the card:
MifareReader.CommPort = 4;
MifareReader.PortOpen = true;
MifareReader.mfRequest();
MessageBox.Show(MifareReader.mfAnticollision().ToString());
MifareReader.mfHalt();
The code is placed inside the backgroundWorkers DoWork method, and the entire method looks like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (!worker.CancellationPending)
{
MifareReader.CommPort = 4;
MifareReader.PortOpen = true;
MifareReader.mfRequest();
CardID = MifareReader.mfAnticollision().ToString();
MifareReader.mfHalt();
if (CardID != "0" && CardID != string.Empty)
{
e.Result = CardID;
worker.CancelAsync();
break;
}
}
}
The reader I'm using is a PROMAG PCR-310U smart card reader and GNetPlus and MifareReader dll's. I have an application where a parent form creates a child form. That child form reads the smart card's ID and sends it to the parent. The problem is this - the first time I create the child form, the reading process works perfectly but the second time (and every time after that) I create the child, the reader stops working - it returns "0" as the CardID whether the card is present or not. What could cause this error, and how would I fix it?
回答1:
Most likely, the issue is the following:
After closing the first child form the MifareReader
instance isn't disposed or otherwise knows that it no longer is required. That means that it still controls the reader and apparently this blocks access to all other instances trying to access that reader.
One such blocked instance is the MifareReader
instance in the second child form you open.
Try telling the first instance that it no longer is required by closing the port via PortOpen = false;
.
来源:https://stackoverflow.com/questions/16771829/reading-mifare-1k-from-a-winform-application