我写了一个扫描蓝牙设备的小算法并将其添加到我的列表框中。但我得到一个错误:跨线程异常。
我想要的是不断更新我的列表框而没有任何中断。但是添加后的 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;
}
}