我为扫描蓝牙设备编写了一些算法并将其添加到我的列表框中。但我得到一个错误:交叉线程异常。
我想要的是连续更新我的列表框而不会有任何中断。但添加后的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;
}
}
答案 0 :(得分:1)
这是WPF还是WinForms?使用WPF,您只能从UI线程访问控件。要从其他线程访问控件,请调用DispatcherObject.Dispatcher.Invoke或控件上的一个类似方法(所有控件都从DispatcherObject继承)。
我确信WinForms有类似的内容。
答案 1 :(得分:0)
我是偶然发现的,想分享我的解决方案。 :-)
在我编程的构造函数中 CheckForIllegalCrossThreadCalls = FALSE; 这解决了我的问题:-D我认为这不是最好的方法,但是第一次可以永久更新我的列表框。