由于后台线程上的事件而在ui线程上执行方法 [英] Executing a method on ui thread due to an event on background thread

查看:81
本文介绍了由于后台线程上的事件而在ui线程上执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在轮询服务器的后台线程.当有数据时,我想在UI线程上处理数据.如果我存储主窗口的hwnd.

I've got a background thread that is polling a server. When there's data, I want to handle the data on the UI thread. If I store the hwnd of the main window.

如何获取要在UI线程上执行的特定方法static void DataHandler(void* data)?

How can I get a particular method static void DataHandler(void* data) to be executed on the UI thread?

我认为创建一个传递hwnd和函数指针的计时器是可行的.但是有更好的方法吗?我可以使用PostMessage以某种方式调用数据处理程序吗.

I think creating a timer passing the hwnd and the function pointer would work. But is there a better way? Can I use PostMessage to somehow get the datahandler invoked.

而且,我不是在编写UI代码,因此我无法修改消息循环中的任何内容.

Also, I'm not writing the UI code, so I don't have the ability to modify anything in the message loop.

推荐答案

您可以做的一件事-使用线程间的信号对象,也许就像布尔标志一样简单.当数据显示在服务器轮询线程上时,您可以发出信号标记.您可以在UI线程的消息循环中检查此标志.或者,您可以只向UI线程发送自定义窗口消息.

One thing that you could do - use an inter-thread signalling object perhaps as simple as a boolean flag. When data appears on the server polling thread, you can signal the flag. You could check for this flag in the message loop of your UI thread. Alternatively, you could just send the UI thread a custom window message.

现在,我重新阅读您的问题-由于您无法更改UI代码,因此这种方法行不通.您可以使用WIN32 API添加您自己的自定义消息挂钩函数来解决此问题.

Now that I re-read your question - since you can't change the UI code, this approach wouldn't work. You could use the WIN32 API to add your own custom message hook function to fix this problem.

这篇关于由于后台线程上的事件而在ui线程上执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆