如何在运行时替换线程应等待的WaitHandle [英] How to substitute at runtime the WaitHandle that a thread should wait on

查看:80
本文介绍了如何在运行时替换线程应等待的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆