用于线程和不同类的监视器锁定的共享变量

发布于 2025-01-04 23:52:57 字数 202 浏览 6 评论 0原文

我正在开发一个 C# Windows 应用程序,在它们自己的线程中启动不同的类(即:线程 1 中的 Class1 实例、线程 2 中的 Class 2 实例等)。

我正在尝试正确挂起/恢复线程,但我无法弄清楚如何在不同的类和线程之间共享监视器的等待/脉冲的锁定变量。

看来这应该有一个简单的答案,我就是想不出来。我真的很感激任何帮助!

谢谢!

I have a C# Windows application I'm working on where I kick off different classes in their own thread (ie: Class1 instance in Thread 1, Class 2 instance in Thread 2, etc).

I'm trying to correctly suspend/resume the threads, but I can't figure out how to share the lock variables for Wait/Pulse of Monitor between different classes and threads.

It seems like this should have a simple answer, I just can't figure it out. I'd really appreciate any help!

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最好是你 2025-01-11 23:52:57

使用公共静态字段,例如,

public class Sync
{
    public static object LockObject = new object();
    //or any other sync mechanism 
    //AutoResetEvent,ManualResetEvent,Semaphore,CountdownEvent,Mutex etc.
}

use public static fields, for ex.,

public class Sync
{
    public static object LockObject = new object();
    //or any other sync mechanism 
    //AutoResetEvent,ManualResetEvent,Semaphore,CountdownEvent,Mutex etc.
}
小…红帽 2025-01-11 23:52:57

监视器锁定对于同步很有用,但当用作消息传递 API 时,它通常只能扩展到两个线程,因为您需要确切地知道每个线程是否获取消息。

当事情变得复杂时,AutoResetEvent 或 ManualResetEvent 通常更明智,因为它们对时间的要求较低:无论顺序如何,您都可以通过大门。

Monitor locking is useful for shnchronization, but when used as a messaging API it usually only scales to two threads, since you need to know exactly where each to know if it gets the message.

When things get complex, an AutoResetEvent or ManualResetEvent is usually more sensible, as they are less time critical: you get through the gate regardless of ordering.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文