【发布时间】:2015-05-19 08:40:05
【问题描述】:
我无法弄清楚这个错误的原因:
在创建窗口句柄之前,不能对控件调用 Invoke 或 BeginInvoke。
这是我的(剥离的)代码:
private: delegate void MyDelegate(Object^ openFileDialog1);
ListView^ myDelegate;
private: void import_links(Object^ openFileDialog1) {
myDelegate = (gcnew System::Windows::Forms::ListView());
myDelegate->BeginInvoke( gcnew MyDelegate( this, &Form1::import_links ), openFileDialog1);
//do some work here
}
private: System::Void Import_LinkClicked(System::Object^ sender, System::Windows::Forms::LinkLabelLinkClickedEventArgs^ e) {
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
Thread^ importThread = gcnew Thread(gcnew ParameterizedThreadStart(this,&Form1::import_links));
importThread->Start(openFileDialog1);
}
}
请告诉我解决方案。
【问题讨论】:
-
如果我添加这个条件:if(myDelegate->InvokeRequired),然后我得到跨线程操作不允许错误。
-
调用
myDelegate->CreateControl()来强制创建句柄,或者只是将控件添加到父控件,确保它是可见的。顺便说一句,你为什么把它命名为myDelegate?这是ListView,当然不是代表。 -
@LucasTrzesniewski 我正在尝试执行跨线程操作,即更新我刚刚在上面的代码中创建的另一个线程中的主线程元素。我知道我的代码有问题。调用 CreateControl() 后,我现在面临此错误:跨线程操作无效。你能告诉我我的代码有什么问题吗?
标签: .net multithreading winforms c++-cli begininvoke