简体   繁体   English

使用TThread与UI线程通信时如何避免使用计时器

[英]How to avoid use of timer when using TThread to communicate with UI thread

I have a TThread which receives and sends to a device on a COM port. 我有一个TThread,可以通过COM端口接收并发送到设备。 After I read the data, I want to activate the GUI (not in the same thread) using Synchronize(function name). 读取数据后,我想使用Synchronize(函数名)激活GUI(不在同一线程中)。 However, when I call the GUI's form function to perform a button click, I get an access violation. 但是,当我调用GUI的form函数执行按钮单击时,出现访问冲突。 I checked to see if the form's value is null and it is not, since this would be an obvious reason for access violation. 我检查了表单的值是否为null或不是,因为这是访问冲突的明显原因。 Right now, I am setting global flags and using a timer that continuously checks to see if a certain condition is met and if so, then I fire off the button click event in that form. 现在,我正在设置全局标志,并使用一个计时器,该计时器连续检查是否满足特定条件,如果满足,则以该形式触发按钮单击事件。 That seems to be the only way to avoid getting the access violation. 这似乎是避免发生访问冲突的唯一方法。

I really don't like timers so is there a way to avoid having to use a timer on the form? 我真的不喜欢计时器,有没有办法避免在表单上使用计时器?

You can post a message to the window in question. 您可以在相关窗口中发布消息。 The timer works in a similar manner. 计时器以类似的方式工作。 It just fires off a windows message inside the form. 它只是在窗体内触发Windows消息。 You obviously have a handle to the window. 显然,您有窗户的把手。

CWnd::PostMessage(...) Don't use send message, it gets processed inline and could cause your thread to stop working. CWnd :: PostMessage(...)不要使用发送消息,它会被内联处理,并可能导致您的线程停止工作。

Typically when you have a worker thread that attempts to access Guithread, they conflict. 通常,当您有一个尝试访问Guithread的辅助线程时,它们会发生冲突。 It's been a while since I've used MFC and threading but that's what I remember. 自从我使用MFC和线程已经有一段时间了,但这就是我所记得的。 I believe it's documented to work that way. 我相信它已被证明可以那样工作。

I found the problem. 我发现了问题。 I thought I was checking if my Form was null, but I was not. 我以为我正在检查我的表格是否为空,但我不是。 I fixed it making sure the form I was referencing is not null . 我已修复它,以确保我引用的表单不​​为null

Edit: Turns out that one of the forms that is called when I call Fbutton1Click() is Modal so it blocks my thread. 编辑:原来,当我调用Fbutton1Click()时被调用的窗体之一是Modal,因此它阻止了我的线程。 I ended having to go back to a timer to call the button click instead.. oh well. 我结束了不得不回到计时器来调用按钮click ..哦,好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM