如何在运行时替换线程应等待的WaitHandle

编程入门 行业动态 更新时间:2024-10-28 16:18:53
本文介绍了如何在运行时替换线程应等待的WaitHandle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道如何在运行时安全地更改线程应等待的EventWaitHandle.

I'm wondering how to safely change at runtime the EventWaitHandle that a thread should wait on.

例如,假设有两个线程(A和C)通过EventWaitHandles同步. A周期性地执行其工作,C一直等待,直到它从A接收到可以开始执行其工作的通知(例如通过AutoResetEvent).模式是A-C-A-C ...

Suppose for instance that there are two threads (A and C) that are synchronized through EventWaitHandles. A does its job cyclically and C waits until it receives notification from A that it can start doing its job (e.g. by the AutoResetEvent). The pattern is A-C-A-C...

稍后在新线程(B)上启动(例如,通过用户操作),并且应以这种方式在两个预先存在的线程之间执行其作业:A进行其作业,然后发出信号B,一旦B完成,则发出信号C .现在的模式是ABCABC ...

Later on a new thread (B) is launched (e.g. by user action) and its job should be executed in between the two preexistent threads in this way: A makes its job, then signals B and once B finishes it signals C. Now the pattern is A-B-C-A-B-C...

因此,在线程C等待与A共享的EventWaitHandle之后,应该有一个安全的机制使C等待与B共享的另一个EventWaitHandle.在我看来,棘手的部分是替换C使用的EventWaitHandle,因为一旦完成,我应该很容易就能启动B,它将使用EventWaitHandle等待A作业,并使用EventWaitHandle发出信号通知C作业.该机制还应该提供一种安全卸载线程B的方法,并返回到只有线程A和C在工作的初始状态.

So before thread C was waiting on the EventWaitHandle shared with A and later there should be a safe mechanism that makes C waiting on another EventWaitHandle shared with B. It seems to me that the tricky part is substituting the EventWaitHandle used by C, since once this is done I should easily be able to launch B that will use a EventWaitHandle to wait on A job and a EventWaitHandle to signal for C job. The mechanism should also provide a way to safely unmount thread B and to go back to the initial situation where only thread A and C are working.

是否存在使用EventWaitHandle完成此操作的安全方法?如果没有,将不胜感激.

Is there a safe way to accomplish this with EventWaitHandle ? If not, any other suggestion would be appreciated.

推荐答案

如果任务A知道更改,则让任务C拥有该事件.如果下一个任务C,则任务A发出任务C的事件信号;如果下一个任务B,则任务B发出信号.

If task A knows about the change, then have task C own the event. Task A signals task C's event if C is to be next, or task B's event if task B is to be next.

或者,使用与更改任何其他共享数据相同的机制:在对句柄的所有访问中获取互斥量.例如任务C获取锁,读取句柄,释放锁,等待句柄.要对其进行更改,您需要让UI线程获取该锁,更改该句柄,然后释放该锁.

Alternatively, use the same mechanism as for changing any other shared data: acquire a mutex across all accesses to the handle. e.g. task C acquires the lock, reads the handle, releases the lock, waits on the handle. To change it you have the UI thread acquire the lock, change the handle, release the lock.

更多推荐

如何在运行时替换线程应等待的WaitHandle

本文发布于:2023-11-26 22:20:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   如何在   WaitHandle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!