简体   繁体   English

从线程更新进度条的最佳方法

[英]Best way to update progress bar from thread

I've got a long-running task that is executed in a thread.我有一个在线程中执行的长时间运行的任务。

The code for this all takes place in a separate class than the WinMain() entry point, say WorkerClass .这一切的代码都发生在一个与WinMain()入口点不同的类中,比如WorkerClass

I'd like to update a progress bar every so often with the progress of the task.我想经常随着任务的进度更新进度条。

After several hours of research, trial, and error, I've come across several methods:经过几个小时的研究、试验和错误,我遇到了几种方法:


A) Custom PostMessage to main window proc from inside the thread (problem: frowned upon by several sources: thread should not touch main UI) A) 从线程内部自定义PostMessage到主窗口 proc (问题:有几个来源不赞成:线程不应该接触主 UI)

B) Custom PostMessage to main window proc from some WorkerClass function (problem: running into scope issues between free vs class functions, since thread function has to be free of class) B) 从一些WorkerClass函数到主窗口 proc 的自定义PostMessage (问题:在自由函数与类函数之间WorkerClass范围问题,因为线程函数必须是自由的类)

C) Worker thread updates int pointer, then a UI-thread timer updates UI periodically (problem: worth spending time on, or is this "doing it wrong") C) 工作线程更新int指针,然后 UI 线程计时器定期更新 UI (问题:值得花时间,还是“做错了”)


A lot of the discussion dives into MFC or C# which I'm not interested in.很多讨论都深入到我不感兴趣的 MFC 或 C# 中。

I'm to the point where I've run into roadblocks with all three methods.我已经到了使用所有三种方法都遇到障碍的地步。 It will be several hours to do a good job on figuring one out - I don't want to put in effort learning it wrong.弄清楚一个问题需要几个小时 - 我不想努力学习错误。

Which one should I pursue?我应该追求哪一个?

FWIW: The code base I currently work on posts a message to the main thread. FWIW:我目前工作的代码库向主线程发布了一条消息。

Another method, and the one I prefer, is the Observer Pattern.另一种方法,也是我更喜欢的方法,是观察者模式。 The main thread would "subscribe" to the worker and whenever the worker updates itself, it notifies its observers (any object that subscribed to it).主线程会“订阅”worker,每当worker更新自己时,它会通知它的观察者(订阅它的任何对象)。 http://en.wikipedia.org/wiki/Observer_pattern http://en.wikipedia.org/wiki/Observer_pattern

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

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