简体   繁体   English

在单独的线程中调用 MFC UI 类上的方法

[英]Calling methods on an MFC UI class in a separate thread

I have two threads in my MFC application.我的 MFC 应用程序中有两个线程。 One of them handles all Wnd stuff and the other some file management.其中一个处理所有 Wnd 内容,另一个处理文件管理。 Is it generally a good idea to call some methods on UI classes from other threads?从其他线程调用 UI 类上的某些方法通常是个好主意吗? Like for example to update some values the UI fields are showing to user.例如,更新 UI 字段向用户显示的某些值。 Or it is a bad practice and I have to send messages to the windows classes?或者这是一种不好的做法,我必须向 Windows 类发送消息? If we try to use locks in UI threads, GUI will freeze frequently which is not really acceptable unless it is for a very trivial job.如果我们尝试在 UI 线程中使用锁,GUI 会频繁冻结,除非它是一项非常琐碎的工作,否则这是不可接受的。 What is the best practice here?这里的最佳做法是什么? Should we solely use message passing mechanisms when dealing with UI?我们应该在处理 UI 时只使用消息传递机制吗?

There are also some methods on UI which don't involve data or variables. UI 上也有一些不涉及数据或变量的方法。 For example telling a window to maximize.例如告诉窗口最大化。 Is it bad to call a public method in UI class in this case?在这种情况下,在 UI 类中调用公共方法是不是很糟糕?

[EDIT] I forgot to tell about my problem with sending messages. [编辑] 我忘了告诉我发送消息的问题。 Your parameters a always two pointers and not easily customizable.你的参数总是两个指针,不容易定制。

Primarily, UI is supposed too be light and responsive.首先,UI 应该是轻量级和响应式的。 To accomplish that, all the heavy duty works should be handled by a separate thread, wherein it can communicate with the main mfc UI thread using SendMessage() .为了实现这一点,所有繁重的工作都应该由一个单独的线程处理,其中它可以使用SendMessage()与主 mfc UI 线程通信。

Commands such as maximizing windows have fairly small overhead and can be accomplished in the UI thread itself.诸如最大化窗口之类的命令具有相当小的开销,并且可以在 UI 线程本身中完成。 To simulate a long process, the UI can use an animated progress bar, for instance.例如,为了模拟一个漫长的过程,UI 可以使用动画进度条。

Decoupling UI from the program engine also will make your code more modular, reusable and the intent clearer.将 UI 与程序引擎解耦也将使您的代码更加模块化、可重用且意图更加清晰。

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

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