简体   繁体   English

时间到时的C#进程和线程终止-等待的计时器

[英]C# Process and Thread Termination When Time is Up - Waitable Timer

I am trying to create the following effect: 我正在尝试创建以下效果:

I have x number of threads running at the same time and I want them all to stop when a timer goes off. 我有x个线程同时运行,我希望它们在计时器关闭时全部停止。

The only thing I can think of doing is having a shared boolean value that changes when the time is up. 我唯一能想到的就是拥有一个共享的布尔值,该值会随着时间的流逝而改变。 Does anyone know how to do this with a threading timer and the AutoResetEvent? 有谁知道如何通过线程计时器和AutoResetEvent做到这一点?

I am having a hard time finding out how to use the Autoreset event... 我很难找出如何使用自动重置事件...

Do you know of a better way to achieve this effect? 您知道实现此效果的更好方法吗?

What about with processes? 流程呢?

Rather than share a boolean, use a ManualResetEvent and have each thread wait on it. 与其共享布尔值,不如使用ManualResetEvent并让每个线程等待它。

private static void ThreadDelegate(object state)
{
    object[] stateArray = (object[])state;
    ManualResetEvent resetEvent = (ManualResetEvent)stateArray[0];

    //Do some work.
    ...

    resetEvent.WaitOne();
}

This will block the thread until you call resetEvent.Set(); 这将阻塞线程,直到您调用resetEvent.Set(); I suppose the best answer to this really depends on how you structure your code. 我想对此的最佳答案实际上取决于您如何构造代码。 What I have suggested depends upon the //Do some work bit doing something like creating a Timer and invoking a callback at some interval. 我的建议取决于//Do some work例如创建一个Timer并每隔一段时间调用一次回调。

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

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