事件复制[wxWidgets编程系列2]_[发送异步事件的注意项之字符串深浅复制]

本文纯属个人见解,是对前面学习的总结,如有描述不正确的地方还请高手指正~

    
1.在任务程线和主程线行进通信时,一般是通过发送事件来同步数据,而任务程线只能发送异步事件,基本不能发送界面绘制相干的同步事件。通信数据时大多情况下须要传递字符串数值,这时候就须要先用使wxEvent的SetString法方,再用使QueueEvent.这里意注了,异步事件是对wxString有所有权的.

    

    以下摘录wx.chm档文里的api说明.

    QueueEvent() can be used for inter-thread communication from the worker threads to the main thread, it is safe in the sense that it uses locking internally and avoids the problem mentioned in AddPendingEvent() documentation by ensuring that the event object is not used by the calling thread any more. Care should still be taken to avoid that some fields of this object are used by it, notably any wxString members of the event object must not be shallow copies of another wxString object as this would result in them still using the same string buffer behind the scenes. For example:

    

    每日一道理
宽容,是一种坦荡,可以无私无畏,无拘无束,无尘无染。宽容,是一种豁达,是比海洋和天空更为博大的胸襟,是宽广和宽厚的叠加,延续和升华。宽容有度,宽容无价,宽以待人,这是人生处世的基本法则。

    wxCommandEvent 通普事件:

void FunctionInAWorkerThread(const wxString& str)
{
	wxCommandEvent* evt = new wxCommandEvent;

	// NOT evt->SetString(str) as this would be a shallow copy 浅复制,就是复制了计数器
	evt->SetString(str.c_str()); // make a deep copy 深复制,连数据一同创建了一个copy.

	wxTheApp->QueueEvent( evt );
}

    

    wxThreadEvent 程线事件:

void FunctionInAWorkerThread(const wxString& str)
{
	wxThreadEvent evt;
	evt->SetString(str);

	// wxThreadEvent::Clone() makes sure that the internal wxString
	// member is not shared by other wxString instances:
	wxTheApp->QueueEvent( evt.Clone() );
}

    2.wxString面里其实就是std::string,用std::string时也要意注点。

string( const string& s ); // a copy of the given string s, 浅复制

string( const char* str ); // a duplicate of str (optionally up to length characters long), 深复制

文章结束给大家分享下程序员的一些笑话语录: 雅虎最擅长的不是开通新业务,是关闭旧业务。

你可能感兴趣的:(wxwidgets)