I'm working on an application that should read the data from Mifare smart card. I have to create a form will check the Mifare reader periodically and when the card is in range, read its serial number and send it to the parent form. I managed to get the background worker to read the serial number, but I can't close the form from it due to cross thread calling error it would cause. Is there a way to monitor the work that backGroundWorker does, and when it successfully reads the card ID, to stop it and close the child form? This is the code I'm using in the DoWork method:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (!worker.CancellationPending)
{
MifareReader.CommPort = 4;
MifareReader.PortOpen = true;
MifareReader.mfAutoMode(true);
MifareReader.mfRequest();
if (CardID == "0" || CardID == string.Empty)
{
MifareReader.mfRequest();
CardID = MifareReader.mfAnticollision().ToString();
MifareReader.mfHalt();
}
else if (CardID != "0" && CardID != string.Empty)
{
MessageBox.Show(ObrnutiID);
worker.CancelAsync();
}
MifareCitac.mfHalt();
}
}
This code does it's job, but I have to manually close the form. Is there a way to check if the CardID variable changes it's value in the main thread and if it does, close the form. I tried to solve this problem by using a timer, but when I do that, the timer blocks the main form thread, and I can't close it manually (which of course I have to be able). Can you please suggest a way to solve this problem?
You can use the BackgroundWorker.RunWorkerCompleted
event to monitor when the BackgroundWorker is done.
Occurs when the background operation has completed, has been canceled, or has raised an exception.
From there, you could close the form programmatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With