当backgroundWorker停止工作时关闭表单

当backgroundWorker停止工作时关闭表单

问题描述:

我正在开发一个应从Mifare智能卡读取数据的应用程序.我必须创建一个表格,该表格将定期检查Mifare读卡器,当卡在范围内时,读取其序列号并将其发送给父表格.我设法让后台工作人员读取了序列号,但是由于跨线程调用会导致错误,因此无法从中关闭表格.有没有一种方法可以监视backGroundWorker所做的工作,并且当它成功读取卡ID时,可以停止它并关闭子窗体? 这是我在DoWork方法中使用的代码:

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();
    }
}

此代码可以完成工作,但是我必须手动关闭表单.有没有一种方法可以检查CardID变量是否在主线程中更改了它的值,如果确实更改了,请关闭表单. 我试图通过使用计时器来解决此问题,但是当我这样做时,计时器会阻塞主窗体线程,并且我无法手动关闭它(当然我必须能够关闭它).您能提出解决此问题的方法吗?

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?

您可以使用BackgroundWorker.RunWorkerCompleted事件来监视BackgroundWorker的完成时间.

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.