0

我写了一个扫描蓝牙设备的小算法并将其添加到我的列表框中。但我得到一个错误:跨线程异常。

我想要的是不断更新我的列表框而没有任何中断。但是添加后的 sleep() 就可以了。

从昨天开始与 Backroundworker 一起尝试,但它不起作用,并且在添加时出现错误。有人有想法。我读过一些关于委托的东西,有人知道吗?

这是我的代码:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
         this->button1->Enabled=false;
         this->button2->Enabled=true;
         this->toolStripStatusLabel1->Text="Active";
         this->toolStripProgressBar1->Value=100;
         this->backgroundWorker1->RunWorkerAsync();

     }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
         this->button1->Enabled=true;
         this->button2->Enabled=false;
         this->toolStripStatusLabel1->Text="Not Active";
         this->toolStripProgressBar1->Value=0;
         this->backgroundWorker1->CancelAsync();
     }
private: System::Void backgroundWorker1_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) {
             BackgroundWorker^ worker = dynamic_cast <BackgroundWorker^> (sender);

             e->Result = Bluetooth(worker,e);
    }

private: System::Void backgroundWorker1_Complete(System::Object^  sender, System::ComponentModel::RunWorkerCompletedEventArgs^  e) {

     }

long Bluetooth (BackgroundWorker^ worker, DoWorkEventArgs ^ e){
    if (worker->CancellationPending){
        e->Cancel=true;
    }
    else{
            vector<wstring> vec;
            int m_device_id=0;
            int m_radio_id = 0;
            m_bt = BluetoothFindFirstRadio(&m_bt_find_radio, &m_radio);
            BluetoothGetRadioInfo(m_radio, &m_bt_info);

            m_search_params.hRadio = m_radio;
            ::ZeroMemory(&m_device_info, sizeof(BLUETOOTH_DEVICE_INFO));
            m_device_info.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
            m_bt_dev = BluetoothFindFirstDevice(&m_search_params, &m_device_info);

            do{
                wostringstream tmp;
                ++m_device_id;

                //Convert Byte in String
                for (int i = 0; i < 6; i++) {
                  tmp << hex << m_device_info.Address.rgBytes [i];
                  if (i < 5)
                    tmp << L':';
                }                   
                //VectorList
                //vec.push_back(tmp.str());

                listBox1->Items->Add(System::Runtime::InteropServices::Marshal::PtrToStringUni(IntPtr((void*) tmp.str().c_str())));
                Sleep(100);
            }while(BluetoothFindNextDevice(m_bt_dev, &m_device_info));
            BluetoothFindDeviceClose(m_bt_dev);
            BluetoothFindRadioClose(m_bt);

            long n=0;
            return n;
    }
}
4

2 回答 2

1

这是 WPF 还是 WinForms?使用 WPF,您只能从 UI 线程访问控件。要从其他线程访问控件,请调用DispatcherObject.Dispatcher.Invoke或控件上的类似方法之一(所有控件都继承自 DispatcherObject)。

我敢肯定 WinForms 也有类似的东西。

于 2012-12-30T15:17:52.917 回答
0

我偶然发现它并想分享我的解决方案。:-)

在构造函数中,我编写了 CheckForIllegalCrossThreadCalls=false; 这解决了我的问题:-DI 认为这不是最好的方法,但首先可以永久更新我的列表框。

于 2012-12-30T15:35:02.130 回答