您好我是C ++新手并尝试处理托管类ServerApi::Request
引发的事件
托管类是一个COM接口,我已使用"添加引用"导入到我的visual studio项目中。用于选择ServerApi.dll文件的工具。所有方法似乎都按预期工作,但事件处理程序onDataReady()
永远不会执行。这是我的代码:
//Event receiver
ref class EventReceiver {
public:
void OnDataReady() {
cout << "dataReadyHandler called" << endl;
}
void AddHandlers(ServerApi::Request^ request) {
request->DataReady += gcnew DataReadyDelegate(this, &EventReceiver::OnDataReady);
}
void RemoveHandlers(ServerApi::Request^ request) {
request->DataReady -= gcnew DataReadyDelegate(this, &EventReceiver::OnDataReady);
}
};
void executeEventRequest() {
ServerApi::RequestManager^ requestManager = gcnew ServerApi::RequestManager();
ServerApi::Request^ request = requestManager->CreateMethod("...");
EventReceiver^ eventReceiver = gcnew EventReceiver();
eventReceiver->AddHandlers(request);
request->Execute();
eventReceiver->RemoveHandlers(request);
}
request
对象在调用DataReady
方法后引发Execute()
事件。我知道数据几乎可以立即从轮询中准备好。我错过了什么?
首次修改
这是我在调用request->Execute()
后最初等待的方式:
EventReceiver^ eventReceiver = gcnew EventReceiver();
eventReceiver->AddHandlers(request);
request->Execute();
clock_t beginTime = clock();
// wait for 2 seconds
while(clock() < beginTime + 2000) {
// do nothing
}
eventReceiver->RemoveHandlers(request);
立即返回Execute方法控件没有阻塞。
答案 0 :(得分:0)
我设法在System::Windows::Forms::Application::DoEvents()
方法中使用executeEventRequest()
来处理DataReady事件:
EventReceiver^ eventReceiver = gcnew EventReceiver();
eventReceiver->AddHandlers(request);
request->Execute();
clock_t beginTime = clock();
// wait for 2 seconds
while(clock() < beginTime + 2000) {
System::Windows:Forms::Application::DoEvents() // this line enabled events handling
}
eventReceiver->RemoveHandlers(request);