问题描述
背景
我的应用程序带有系统任务栏图标。
应用程序通过在两种可视状态(BLINK_ON和BLINK_OFF)之间快速切换来使该图标闪烁。
闪烁必须可中断;当用户左键单击图标时,闪烁循环应中断并以零延迟返回。
实施
我使用事件门控的while循环生成计时器:
blink_states_iterator = iter([
(3.0,BLINK_ON),(0.25,BLINK_OFF),])
blink_timer = None
# Break out of the loop when an event flag is set.
while not CEASE_BLINKING.is_set():
# If the prevIoUs Timer is no longer running...
if blink_timer is None or not blink_timer.is_alive():
try:
time_until_next_state,next_blink_state = next(blink_states_iterator)
# Restart the iterator each time it exhausts the list of states.
except stopiteration:
blink_states_iterator = iter(blink_states_list)
time_until_next_state,next_blink_state = next(blink_states_iterator)
# Create a new Timer to execute the blink state change after its interval has elapsed.
blink_timer = threading.Timer(
interval=time_until_next_state,function=change_blink_state,args=(next_blink_state,))
blink_timer.start()
# Otherwise,a Timer is still running,and nothing should be done right Now.
else:
# An imperceptibly short delay keeps this loop from hogging the cpu.
time.sleep(0.1)
# Once out of the loop,immediately stop the timer before execution occurs.
if blink_timer:
blink_timer.cancel()
结果
此代码完成了应做的工作。但是,the Concurrency Diagram concerns me:每个循环都会产生并终止一个全新的线程。该循环可能每秒发生4次,并且可能无限期地持续。
问题
- 像这样的不确定循环中产生和终止线程是否有负面影响?
- 如果是,是否有更好的方法来实现此行为?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)