I am working on an application that should read data from a Mifare smart card. I have to create a form that 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 cannot close the form due to the cross-flow error that this would cause. Is there a way to control the work that backGroundWorker is doing 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 the job, but I need to manually close the form. Is there a way to check if the CardID variable will change its value in the main thread, and if that happens, close the form. I tried to solve this problem using a timer, but when I do this, the timer blocks the flow of the main form and I cannot close it manually (which, of course, I should be able to). Can you suggest a way to solve this problem?
source share