2

我有一个 GUI 和一个工作线程,我想将数据从工作线程发送到 GUI。我正在使用 QueueEvent 和 wxThreadEvents 来保持模型视图分离。我以某种方式遇到了 baadf00d 错误。

const int EvtID = 42;

MyFrame::MyFrame()
{
  ...
  // this seems to work correctly,
  //   but I'm including it in case it is part of the problem
  Bind(wxEVT_THREAD, (wxObjectEventFunction)&MyFrame::OutputData, this, EvtID);
  ...
}

MyFrame::OutputData(wxThreadEvent* event)
{
  // should get data from MyThread,
  //   but outputs 0xBA, 0xAD, 0xF0, 0x0D in successive calls
  output << event->GetInt();
}

MyThread::CreateOutputWithLocal()
{
  wxThreadEvent event(wxEVT_THREAD, EvtID);
  event.SetInt(getData());
  //pFrame is a wxEvtHandler*
  pFrame->QueueEvent(event.Clone());
}

MyThread::CreateOutputWithPointer()
{
  wxThreadEvent* event = new wxThreadEvent(wxEVT_THREAD, EvtID);
  event->SetInt(getData());
  //pFrame is a wxEvtHandler*
  pFrame->QueueEvent(event); // QueueEvent() takes control of the pointer and deletes it
}

使用wxThreadEvent's SetPayload()andGetPayload()或 its SetExtraLong()andGetExtraLong()似乎没有任何区别。我需要什么才能让它工作?

4

2 回答 2

1

Set/GetPayload 应该可以解决问题。可能是你做错了。您的代码将有更多帮助。但这里是一个剥离的例子,展示了这两种方法的用法。

Connect(wxID_ANY, wxEVT_COMMAND_DATA_SENT, wxThreadEventHandler(GMainFrame::OnAddText), NULL, this);//connect event to a method

void* MyThread::Entry(){
    wxThreadEvent e(wxEVT_COMMAND_DATA_SENT);//declared and implemented somewhere
    wxString text("I am sent!");
    e.SetPayload(wxString::Format("%s", text.c_str()));
    theParent->GetEventHandler()->AddPendingEvent(e);
    return NULL;
}


void GMainFrame::OnAddText(wxThreadEvent& event) {
    wxString t = event.GetPayload<wxString>();
    wxMessageBox(t);
}

我很久以前在玩 wxThreadEvent 时写的一个示例的剥离版本

于 2012-11-06T07:18:46.483 回答
0

在您的情况下,我只会将有效负载存储在属于框架的线程安全队列中。

Before you queue the event, queue the data in the thread safe queue. In the OutputData function, flush the queue and read the data that is in it.

I'm using this strategy to pass boost::function < void () > to the UI, so it's very scallable, because I can trigger almost anything from the engine thread.

于 2012-11-15T14:40:44.707 回答